HowTo : Read a file Line By Line

If you need to read each line from a file and perform some action with it, then you can use 'while' loop.


while read line; do [COMMAND]; done < [INPUT_FILE]

Single Line Example

The next command will print the file 'file.txt' line by line, adding "This is a line :" at the beginning of each line.

while read line; do echo "$line"; done < file.txt

BASH Script

The next script will print file line by line :

while read line; do
     echo "This is a line : $line"
done < $FILE

Save and execute the script :
chmod +x
./ /etc/passwd
This is a line : root:x:0:0:root:/root:/bin/bash
This is a line : bin:x:1:1:bin:/bin:/sbin/nologin
This is a line : daemon:x:2:2:daemon:/sbin:/sbin/nologin