bash action: BASH SCRIPT FOR LOOP


Hello together,

today i want to give you some nice hints how to handle some operations like moving, deleting, reading content for a bunch of files with less spending time.
The trick is to using the mighty bash and a loop function. There are existing some loop-possibilities f.e. the while-loop for the linux or unix-bash, but in this small tutorial we will be focused on the bash script for loop.

If you have problems with some loops or you want create a more complex loop – please ask me. askme@infofreund.de

Requirements:

bash 🙂

Let’s start:

Before we start, we need the command for listing all files for a directory and the subdirectories.
i created a folder „testfolder“ for my examples – you have to replace it with your foldername.

the command for listing is:

find testfolder -type f

1 bash script for loop: renaming the ending of all files to „.text“:

If you know the ending f.e: „.txt“

for i in `find testfolder -type f`
do
mv `echo $i` `echo $i | sed -e "s/\.txt/\.text/g"`
done

If you dont know the ending

for i in `find testfolder -type f`
do
mv `echo $i` `echo $i | sed -e "s/\..*$/\.text/g"`
done

2 bash script for loop: moving files to a different folder „/tmp/newfolder“:

for i in `find testfolder -type f`
do
mv `echo $i` /tmp/newfolder/.
done

3 bash script for loop: copying files to a different folder „/tmp/newfolder“:

for i in `find testfolder -type f`
do
cp `echo $i` /tmp/newfolder/.
done

4 bash script for loop: showing content of files:

for i in `find testfolder -type f`
do
cat `echo $i`
done

if you want the corresponding filename:

for i in `find testfolder -type f`
do
if [ `cat $i | wc -m` -gt 0 ]
then
echo $i
cat `echo $i`
fi
done

5 bash script for loop: deleting all files in the folder „testfolder“:

for i in `find testfolder -type f`
do
rm `echo $i`
done

Hint: Before you start to do loops with destructive commands like rm or mv, please use the echo-command in the loop first.

for i in `find testfolder -type f`
do
echo $i
done

6 bash script for loop: parsing a file :

You can do the operations we did on the folder for file content too. Dont forget the IFS= at the beginning, because if you don’t set it, spaces will do a line break too.

IFS='
'
for i in `cat file`
do
echo $i
done

7 bash script for loop: iterate a number:

for i in {1..10} 
do echo $i 
done

Output:

1
2
3
4
5
6
7
8
9
10

Kommentare sind abgeschaltet.