Tuesday, January 12, 2010

Bash: reading lines from a file

I guess I don't do this enough to remember it:

When reading a file in a for loop in bash, the following idiom will read each work (whitespace delimited):
for word in `cat file.txt`; do echo $word; done

If you want to grab the whole line then you can do this:
while read line; do echo $line; done < file.txt

or
cat file.txt | while read line; do echo $line; done

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete