User Tools

Site Tools


cs370:cs_370_-_reading_lines_from_files

Reading Lines From Files

While Read

The shell read command inputs entire lines.

We can do the following to send a file, line by line, to a while read loop:

# Non-ideal method.
# File we are going to process is represented by $filename.
cat $filename |
while read line; do
   echo $line   # simple echo of each line
done

But some people have a problem with this. They say that you should instead do the following, which represents the “BEST” way to read a file line by line in a shell script:

# BEST method.
# File we are going to process is represented by $filename.
while read line; do
   echo $line   # simple echo of each line
done < $filename

For Loop

For files that contain only one word or one field per line, where it is guaranteed that no white space characters will appear, a for loop can be used like this:

# WORST method.
# File we are going to process is represented by $filename.
for line in $(cat $filename); do
   echo $line   # simple echo of each line
done

This is considered the absolute "WORST" way to try to read a file, line by line. But a Bash internal variable ($IFS) (internal field separator) can mitigate this for files that contain more than one word per line. See examples at http://en.kioskea.net/faq/1757-how-to-read-a-file-line-by-line.


cs370/cs_370_-_reading_lines_from_files.txt · Last modified: 2017/09/26 14:02 by jchung

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki