-
24 June 2010, 23:29
Bash: How to Loop Through Lines in a File
This is a post that I've wanted to do for a long time. It's not something that is obvious, but it is very necessary for a lot of different scripting scenarios. For instance, in one recent project, I had a text file where each line was a sudoku puzzle generated by gnome-sudoku. I wanted to use each line of that file to provide input for a sudoku solver I was writing.
The first thing that I thought to do was use a for-loop similar to how you would read files in a directory:
for line in $(cat $filename); do echo "$line" doneAnd that might work for you. But it will not work if you have any spaces in a line, like I did. Basically, spaces of any kind are used as the delimiter. There's a better way that will read the entire line every time.
while read line; do echo "$line" done < "$filename"It might seem strange, but you can pipe a file into a while loop. This while loop will use the
readcommand to read lines of input from$filenameand assign the current line to the aptly named$linevariable. This will continue until EOF is read.