![](/img/trans.png)
[英]Recursive bash script to rename files and folders with specific rules on Mac/Linux
[英]How to make a bash script classify files in folders by a specific number
我在StackOverflow上找到了一個腳本,我對其做了一些修改。 該腳本將子文件夾中文件夾中的所有文件分類,每個子文件夾中只有8個文件。 但是我有這樣名稱的文件0541_2pcs.jpg。 2pcs表示兩件(副本)。
因此,我希望腳本在將文件划分到每個文件夾時考慮到這一點。 例如,一個文件夾可能包含6個文件,而這個0541_2pcs.jpg實際意味着2個文件,依此類推,具體取決於文件名中指示的編號。
這是腳本:
cd photos;
dir="${1-.}"
x="${1-8}"
let n=0
let sub=0
while IFS= read -r file ; do
if [ $(bc <<< "$n % $x") -eq 0 ] ; then
let sub+=1
mkdir -p "Page-$sub"
n=0
fi
mv "$file" "Page-$sub"
let n+=1
done < <(find "$dir" -maxdepth 1 -type f)
誰能幫我?
您可以通過[ ${file/2pcs/x} != $file ]
這樣的代碼來添加文件名是否包含字符串“ 2pcs”的測試。 在下面顯示的腳本中,如果該測試成功,則第二次增加n
。 請注意,如果第八個文件被測試要包含在目錄中,則它是一個多段文件,那么在該目錄中最終會有一個文件太多。 可以通過腳本不執行的其他測試來解決。 請注意,您的腳本沒有充分的理由調用bc
進行模量計算,並且從第一個參數設置dir
和x
均無效。 我的腳本使用兩個參數。
#!/bin/bash
# To test pagescript, create dirs four and five in a tmp dir.
# In four, say
# for i in {01..30}; do touch $i.jpg; done
# for i in 03 04 05 11 16 17 18; do mv $i.jpg ${i}_2pcs.jpg; done
# Then in the tmp dir, say
# rm -rf Page-*; cp four/* five/; ../pagescript five; ls -R
#cd photos; # Leave commented out when testing script as above
dir="${1-.}" # Optional first param is source directory
x=${2-8} # Optional 2nd param is files-per-result-dir
let n=x
let sub=0
for file in $(find "$dir" -maxdepth 1 -type f)
do # Uncomment next line to see values as script runs
#echo file is $file, n is $n, sub is $sub, dir is $dir, x is $x
if [ $n -ge $x ]; then
let sub+=1
mkdir -p Page-$sub
n=0
fi
mv "$file" Page-$sub
[ ${file/2pcs/x} != $file ] && let n+=1
let n+=1
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.