Attention: open in a new window. PDFPrint

Read It Linewise

Ever been in the need to read a text file linewise using a bash script?

I mostly perform line operations using awk or sed but from time to time there are some problems I have to solve that are to hard to solve using this tools. For this, there is a simple way to read a file linewise using a simple bash script:

# get one filename
FILENAME="Just A Filename"

# backup the old ifs and set it to newline
OIFS="$IFS"
IFS=$'\n'

for LINE in $(cat "$FILENAME"); do
# process your lines here
done

# reset the ifs variable
IFS="$OIFS"

The IFS-variable changes the behaviour of the for-loop an whitespaces. Normally the for loop would use any whitespace (tabulator, space, linebreak) as token delimiter. By setting the IFS to \n we only use the newline token as token delimiter and we can read our file linewise.