Shell Script Usage Notes

Update 05.18.2018  For loop usage

Case 1: rename all file of directory in command line.

Assume that there are 5 files in a directory as following.
f1.txt
f2.txt
f3.txt
f4.txt
f5.txt
Get files to an array.
$ FILES=($(ls))
Print all files
$ echo ${FILES[@]}
f1.txt f2.txt f3.txt f4.txt f5.txt
Print file count
$ echo ${#FILES[@]}
5
Syntax to iterate using for loop
$ for ((i=0; i<<#NUMBER>; i++)); \
   do <#COMMAND>; \
done; 
Let's rename all the files.
//Usage 1
$ for ((i=0; i<${#FILES[@]}; i++)); \
   do mv ${FILES[$i]} "new-$i.txt"; \
done;

//Usage 2
$ i=0; for j in ./*.txt; \
   do mv $j "new-$((i++)).txt"; \
done

//Usage 3
$ for i in $(seq 0 $((${#FILES[@]}-1))); \
   do mv ${FILES[$i]} "new-$i.txt"; \
done
Result:
new-0.txt
new-1.txt
new-2.txt
new-3.txt
new-4.txt

References 


Share:

0 意見:

張貼留言