-->

How to read file Line by Line using Linux Shell Script

Author Piyush Gupta

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:

  1. The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line
  2. while read -r line; do COMMAND; done < input.file
  3. The -r option passed to read command prevents backslash escapes from being interpreted.
  4. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed -
  5. 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:
#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r line
do
  echo "$line"
done < "$input"
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.
#!/bin/bash

while read line
do
    USERNAME=`echo $line | cut -d":" -f1`
    HOMEDIR=`echo $line | cut -d":" -f6`
    echo "$USERNAME =>  $HOMEDIR"
done < /etc/passwd

No comments:

Post a Comment