Knowing for loop in bash is definitely one of the most powerful tricks. For instance, it makes processing and reading files quick and painless in most cases. Since there can be countless use cases for this, i will write down some basic use scenarios.
Here is few basic examples that could be useful.
Creating files:
Renaming all files within directory:
Here is few basic examples that could be useful.
Creating files:
for i in 1 2 3 4;do touch file"$i";done
ls -l
-rw-r--r-- 1 m 5000 0 Feb 26 21:31 file1
-rw-r--r-- 1 m 5000 0 Feb 26 21:31 file2
-rw-r--r-- 1 m 5000 0 Feb 26 21:31 file3
-rw-r--r-- 1 m 5000 0 Feb 26 21:31 file4
Renaming all files within directory:
ls -l
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic01.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic02.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic03.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic04.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic05.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic06.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic07.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic08.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic09.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic10.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic11.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic12.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic13.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic14.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic15.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic16.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic17.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic18.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic19.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 pic20.JPG
I want to change rename these pictures as picture_01, picture_02 and so on. I could do this:
for i in *;do mv $i $(echo $i | sed "s/pic/picture_/");done
ls -l
total 0
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_01.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_02.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_03.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_04.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_05.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_06.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_07.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_08.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_09.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_10.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_11.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_12.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_13.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_14.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_15.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_16.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_17.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_18.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_19.JPG
-rw-r--r-- 1 m 5000 0 Feb 26 21:18 picture_20.JPG
* wildcard in this bash loop (for i in *) refers to all files within current working directory. That's why this for loop will catch all files.
No comments:
Post a Comment