我試圖對數千個檔案進行排序,并根據檔案擴展名將它們放在自己的檔案夾中。例如,將 JPG 檔案放入 JPG 檔案夾。
如何創建 for 回圈來解決這個問題?
我試圖做到的:
# This listed out all the file extensions and the count for each extension:
find . -type f | rev | cut -d. -f1 | rev | tr '[:upper:]' '[:lower:]' | sort | uniq --count | sort -rn
#This was able to find all jpegs in the media folder
find /media -iname '*.jpg'
# This worked, however the MV command does not create the folder
find /media -iname '*.jpg' -exec mv '{}' /media/genesis/Passport/consolidated/jpg/ \; #
我猜 for 回圈會是這樣的,但我似乎無法弄清楚:
for dir in 'find /media -iname "*.jpg"'; do
mkdir $dir;
mv $dir/*;
done
uj5u.com熱心網友回復:
你可以試試這個腳本。
它應該找到其中的所有檔案/media并將其移動到pwd.
$ cat locate.sh
#!/usr/bin/env bash
for files in $(find /media -type f); do
dir=$(echo "$files" | sed 's/.[^.]*.\(.*\)/\1/g')
loc_path=$(pwd)/"$dir"
if [[ ! -d "$loc_path" ]]; then
mkdir "$loc_path" &>/dev/null
mv "$files" "$loc_path"
else
mv "$files" "$loc_path"
fi
done
注意:請在實際資料上使用前進行測驗。
uj5u.com熱心網友回復:
要查找特定擴展名的所有檔案并將其移動到目的地,我們可以使用find如下命令:
find . -name "*.jpg" -exec mv {} $destination/ \;
這是關鍵邏輯,您可以在此基礎上創建一個 for 回圈來遍歷媒體檔案夾中的所有已知檔案擴展名
## List all the known extensions in your media folder.
declare -a arr=("jpg" "png" "svg")
## Refer question 1842254 to get all the extentsions in your folder.
## find . -type f | perl -ne 'print $1 if m/\.([^.\/] )$/' | sort -u
## now loop through the above array
for i in "${arr[@]}"
do
echo "$i"
## Create a directory based on file extension
destination="$i"
mkdir $destination
find /media -iname "*.$i" -exec mv {} $destination/ \;
done
請注意,您可以根據需要更改目的地。我只是把它留在同一個目錄中。
這是一個可執行的 shell 腳本供您參考:https : //onlinegdb.com/NEQSpojhM
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359460.html
