我正在嘗試創建一個 shell 腳本,它將創建指定數量的多個檔案(或一批檔案)。當達到金額時,腳本停止。重新執行腳本時,檔案將從上次創建的檔案中選取。因此,如果腳本在第一次運行時創建檔案 1-10,那么在下一次腳本執行時應該創建 11-20,依此類推。
enter code here
#!/bin/bash
NAME=XXXX
valid=true
NUMBER=1
while [ $NUMBER -le 5 ];
do
touch $NAME$NUMBER
((NUMBER ))
echo $NUMBER "batch created"
if [ $NUMBER == 5 ];
then
break
fi
touch $NAME$NUMBER
((NUMBER 5))
echo "batch complete"
done
uj5u.com熱心網友回復:
根據我上面的評論和您的描述,您可以撰寫一個腳本,每次運行時都會創建 10 個編號檔案(默認情況下),從下一個可用編號開始。如上所述,與其僅使用未填充的原始數字,一般排序和串列最好使用填充零的數字,例如001, 002, ...
如果您只使用1, 2, ... 那么當您達到 的每個冪時,您最終會得到奇數排序10。考慮1...12沒有填充編號的前 12 個檔案。一般串列排序會產生:
file1
file11
file12
file2
file3
file4
...
Where11和12都排在了之前2。添加前導零printf -v可以避免這個問題。
考慮到這一點,并允許用戶通過將其作為引數來更改前綴(檔案名的第一部分),并通過將計數作為第二個引數傳遞來更改要創建的新檔案的數量,您可以這樣做就像是:
#!/bin/bash
prefix="${1:-file_}" ## beginning of filename
number=1 ## start number to look for
ext="txt" ## file extension to add
newcount="${2:-10}" ## count of new files to create
printf -v num "d" "$number" ## create 3-digit start number
fname="$prefix$num.$ext" ## form first filename
while [ -e "$fname" ]; do ## while filename exists
number=$((number 1)) ## increment number
printf -v num "d" "$number" ## form 3-digit number
fname="$prefix$num.$ext" ## form filename
done
while ((newcount--)); do ## loop newcount times
touch "$fname" ## create filename
((! newcount)) && break; ## newcount 0, break (optional)
number=$((number 1)) ## increment number
printf -v num "d" "$number" ## form 3-digit number
fname="$prefix$num.$ext" ## form filename
done
不帶引數運行腳本將創建前 10 個檔案file_001.txt- file_010.txt。第二次運行,它會再創建 10 個檔案file_011.txt到file_020.txt.
要使用 前綴創建一個由 5 個檔案組成的新組list_,您可以執行以下操作:
bash scriptname list_ 5
這將導致 5 個檔案list_001.txt變為list_005.txt. 使用相同的選項再次運行會造成list_006.txt對list_010.txt。
Since the scheme above with 3 digits is limited to 1000 files max (if you include 000), there isn't a big need to get the number from the last file written (bash can count to 1000 quite fast). However, if you used 7-digits, for 10 million files, then you would want to parse the last number with ls -1 | tail -n 1 (or version sort and choose the last file). Something like the following would do:
number=$(ls -1 "$prefix"* | tail -n 1 | grep -o '[1-9][0-9]*')
(note: that is ls -(one) not ls -(ell))
Let me know if that is what you are looking for.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359471.html
