shell script to read data from text file

Shell Script to Read Data from Text File using For Loop

Often you may need to read data from text file in shell script. There are several ways to do this in Linux. In this article, we will learn how to read data from text file using for loop, do while, as well as echo.


Shell Script to Read Data from Text File using For Loop

Let us say you have the following file data.txt in Linux with each line having one day of the week.

cat data.txt
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Let us look at the different ways to read the file.


Using For Loop

In this case, we store the result of cat command in a temporary variable of for loop and iterate through each line of it. In each iteration, we use echo command to print the line.

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


Using While Command

You can also use do-while command to read the file. It is similar to the above for loop. One difference is that we input filename at the end of the do-while-done command.

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

In while loop, we use read command to read one line from the file, as long as there are unread lines in it, and store it LINE variable. In each iteration, we use echo command to display value of $LINE variable. But the above code will skip blank lines. If you also want to read and print blank lines, modify the while loop’s condition as shown below.

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


Using Echo Command

You can also use echo command to display file contents but in this case, it will display all file contents on a single line.

$ echo $( < data.txt )
Monday Tuesday Wednesday Thursday Friday Saturday Sunday

In this short article, we have learnt how to read lines of text file one by one and display their contents. Also read:

Awk Split One Column into Multiple Columns
How to Read Variable From File in Shell Script
Shell Script to Print Output in Table Format
How to Change PHP Version in Ubuntu
MySQL Clustered Index

Leave a Reply

Your email address will not be published. Required fields are marked *