read line by line

October 18th, 2006 mysurface Posted in Bash, read | Hits: 47939 | 2 Comments »

When writting shell script, usually people are looking for how to read line by line and manipulate the lines, the simple way of using “read” shows as bellow

while read line
do
  echo "__ $line"
done < file.txt

The example above simple add 2 underscore and a space infront of each line.

By default read is line by line, what if you want to read different field, each of them seperate by a “space”? You need to use a global environment variable IFS(input field separator). You do this,

#we store the original IFS
O=$IFS; IFS=" ";
while read e1 e2
do
  echo "__ $e1 _ $e2 "
done < file.txt;
#revert back the IFS
IFS=$O;

But read works differently compare to awk and cut, it have some problem, let say your file.txt as bellow

firstname lastname age sex location

By running the script above, it $e2 will store “lastname age sex location” instead of “lastname” only. So what if I want to get firstname and lastname only? I need to place another variable to store all junk.

#we store the original IFS
O=$IFS; IFS=" ";
while read e1 e2 junk
do
  echo "__ $e1 _ $e2 "
done < file.txt;
#revert back the IFS
IFS=$O;

What if I want to read from string instead of read from file?

#we store the original IFS
O=$IFS; IFS=" ";
while read e1 e2 junk
do
  echo "__ $e1 _ $e2 "
done <<< "Bobby Lee is on the show";
#revert back the IFS
IFS=$O;

2 Responses to “read line by line”

  1. it is a good example it helped me thanks alot

  2. Hi,
    I want to read each file from a directory (please note each file has only one line record of maximum 10 characters)

    I want to display name of the file and its corrosponding contet on the same line

    for e.g.
    1) abc.txt 123456 (this is expected output)
    2) abc.txt
    123456 (This is not expected output, since content of file is on next line)
    Please advise if I could write a shell script in UNIX (korn shell) to get the desired output

Leave a Reply