Author : Piyush Gupta
You can use while..do to read file line by line on a Linux or Unix-like system.
You can use while..do to read file line by line on a Linux or Unix-like system.
Syntax: Read file line by line on a Bash Unix & Linux shell:
- The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line
- while read -r line; do COMMAND; done < input.file
- The -r option passed to read command prevents backslash escapes from being interpreted.
- Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed -
- while IFS= read -r line; do COMMAND_on $line; done < input.file
Example:-
How to Read a File Line By Line in Bash
Here is more human readable syntax for you:
The input file ($input) is the name of the file you need use by the read command. The read command reads the file line by line, assigning each line to the $line bash shell variable. Once all lines are read from the file the bash while loop will stop. The internal field separator (IFS) is set to the empty string to preserve white-space issues. This is a fail-safe feature.
How to read a file Line By Line using Shell Script
Some times we required to read file content line by line inside shell a script. For this example this script will read /etc/passwd file line by line and print usernames with there corresponding home directory.
No comments:
Post a Comment