How to read a file line by line
Intro
One of the most common errors of learning scripts bash on GNU / Linux is to read a file line by line, is to use a loop "for" (for line in $ (cat file.txt) do. ..), which in this example leads to an assessment for li not every word of the file.
Sample output with a loop "for":
for line in $ (cat file.txt) do echo "$ line" done
This
is
the
row
No
1
This
is
the
row
No
2
This
[...]
The solution is to use a loop "while" coupled with the internal read.
But it is possible to get me the result with a loop "for" provided to change the value of the variable $ IFS (Internal Field Separator, internal field separator) before starting the loop. This is what we will see more ...
While loop
The loop "while" remains the most appropriate and easiest way to read a file line by line.
Syntax
while read line
do
command
done <file
==Example==
The starting file:
This is the No. 1 line
This is line 2
This is the line # 3
This is the line n ° 4
This is the line # 5
The instructions from the command line:
while read line; do echo-e "$ line \ n" done <file.txt
or in a script "bash":
#! / bin / bash
while read line
do
echo-e "$ line \ n"
done <file.txt
The output on the screen (stdout):
This is the No. 1 line
This is line 2
This is the line # 3
This is the line n ° 4
This is the line # 5
Tips
It is entirely possible from a structured file (like an address book or / etc / passwd for example), retrieve the values of each field and assigned to several variables with the command "read" . Be careful to properly assign the variable IFS "good field separator (space by default).
Example:
#! / bin / bash
while IFS =: read user pass full uid gid home shell
do
echo-e "$ full: \ n \
Username: $ user \ n \
UID: \ t $ uid \ n \
GID: \ t $ gid \ n \
Home: \ t $ home \ n \
Shell: \ t $ shell \ n \ n "
done </ etc / passwd
Bonus
while read
i; do echo-e "Parameter: $ i" done <<(echo-e "a \ nab \ nc")
For loop
If the loop "while" is despite the easiest method, it has its side effect, however, that it obliterates the formatting lines including spaces and tabs - \
Moreover the loop "for" coupled with a change of IFS helps keep the structure of the document output.
Syntax
oldIFS = $ IFS # save the field separator
IFS = $ '\ n' # new field separator, the end of line
for line in $ (cat file)
do
command
done
IFS = $ # old_IFS restoration of field separator default