Looping through the content of a file in Bash

Operating SystemLinuxMCA

Often it is a requirement to read each of the line from a file using a bash script. There are various approaches to read the lines form a file. In the below example we have first described how to create a sample file and then run a script reading that sample file.

Create a file to Read

# Open vi Editor
vi a_file.txt
# Input the below lines
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
# cat the file
cat a_file.txt

Running the above code gives us the following result −

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Using Do-While

In this approach we use a do-while loop to read a file. We give the file name as an input at the end of the file. First we create a script and give the execute permission to it. Then only it can read the file and show the result.

#!/bin/bash
while read LINE
do echo "$LINE"
done < a_file.txt

Running the above code gives us the following result −

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Using for and in

In next approach we use a for loop along with the in clause. Here we store the result of cat command (which is each line) in a variable which is part of for loop and echo the variable.

#!/bin/bash
file=a_file.txt
for i in `cat $file`
do
echo "$i"
done

Running the above code gives us the following result −

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

With only echo

We can also get the content of the file by using only echo. But the result will come out as an array of lines and printed out as one-line output showing combination of all the lines.

echo $( < a_file.txt )

Running the above code gives us the following result:

Monday Tuesday Wednesday Thursday Friday Saturday Sunday

Reading File with Blank Lines

If a file has some lines which are blank then we ca avoid them in the output by using the following code. This uses the IFS (internal Field Separator) is set to empty string so that the blank lines are treated as field separator and avoided in the output. Assuming there are blank lines between 3rd and 4th line, those blank liens will not be printed.

#!/bin/bash
while IFS = read -r LINE
do echo "$LINE"
done < a_file.txt

Running the above code gives us the following result −

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
raja
Published on 03-Jan-2020 11:45:05
Advertisements