Wednesday, May 30, 2012

How to Read a File Line By Line in Shell Script(Bash) and Process Each Line in The Loop

Bash/Shell Script to Read  A File Line By Line 

I found a lot of different ways to read the file line by line in shell script.
Also I had a hard time to process the line read inside the loop.

Thought of documenting the solution so that others don't have to go through the frustration I did.

Here it goes...

#Code to Read a File Fine by Line In Shell Script(bash)
#AND
#Process Line in the the loop

while read line
do
 current_line=$(echo $line)
 modified_line="Hi "$current_line
 echo $modified_line
done < file_You_Want_To_READ.txt

Explanation:
  • Here file_You_Want_To_READ.txt is the file present in the same directory as your script. This is the file you want to process line by line.
  • The loop stores each line in a variable called line
  • If I want to process that variable line, then it has to be stored in another variable,current_line by using $(echo $line)
  • Then I create another variable modified_line that'll just prepend "Hi" to it. Then I just print it.
If the file file_You_Want_To_READ.txt looks like this:
Abhi
Nandan

Then the output will be :
Hi Abhi
Hi Nandan

2 comments: