Friday, 24 June 2016

Shell Script To Read a Text File Line by Line

Here i am going to show you two methods of reading a text file with shell script. For our entire exercise consider a demo.txt file which having the following contents .

mukesh@ubuntu:~/Desktop$ cat demo.txt
this is line one
Hello everyone\\ how are you.
this is\ line third with back slash.
This is sample last line.


Method 01: cat file then read line

#! /bin/bash

# Script name : readFile.sh
# Description : Script will read demo.txt which is in current directory.

cat demo.txt | while read LINE
do
        echo $LINE
done


Output:
this is line one
Hello everyone\ how are you.
this is line third with back slash.
This is sample last line.



Method2: Redirecting file into while loop and then read line.

#! /bin/bash

# Script name : readFile.sh
# Description : Script will read demo.txt which is in current directory.

while read LINE
do
    #do what you want to $LINE
    echo $LINE
done < demo.txt

Output:
this is line one
Hello everyone\ how are you.
this is line third with back slash.
This is sample last line.


Note:
If you observe above both the program you will notice in the output back slash "\" is in not printing.
This is happening because program treating "\" as a special character. To avoid this problem use -r while reading line as in the following script.

#!/bin/bash
# Script name : readFile.sh
# Description : Script reading the demo.txt file line by line and treating backslash as a normal character.


if [ $# -ne 1 ]
then
    echo "Usage : $0 filename "
    echo "Give the file name as command line argument."
    echo "Ex.: $0 demo.txt"
    exit 1
fi

filename="$1"

while read -r LINE
do
    echo "$LINE"
done < "$filename"


Output:
this is line one
Hello everyone\\ how are you.
this is\ line third with back slash.
This is sample last line.


where :
-r  Do not treat a backslash character in any special way.
    Consider each backslash to be part of the input line.
   

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...