Sunday, January 12, 2014

Read files line by line using simple script.

2. Read files line by line using simple script.

[saikrishna.b@gai-1339 Documents]$ cat testfile
This is a sample script.
To test
the file is read line by line.
Hope this works.
Lets c.
Done

[saikrishna.b@gai-1339 Documents]$ cat line.sh
#!/bin/bash
filename=$1
count=0
cat $filename | while read a
do
let count++
echo " $count $a "
done

[saikrishna.b@gai-1339 Documents]$ sh line.sh testfile
 1 This is a sample script.
 2 To test
 3 the file is read line by line.
 4 Hope this works.
 5 Lets c.
 6 Done

[saikrishna.b@gai-1339 Documents]$ cat line.sh
#!/bin/bash
filename=$1
count=0
cat $filename | while read a
do
let count++
echo " $count $a "
done
echo -e "\n Total $count lines read" #Add this line to see how many line read is working.

[saikrishna.b@gai-1339 Documents]$ sh line.sh testfile
 1 This is a sample script.                          
 2 To test                                          
 3 the file is read line by line.                    
 4 Hope this works.
 5 Lets c.
 6 Done

 Total 0 lines read

Instead use the below syntax to count the lines.

[saikrishna.b@gai-1339 Documents]$ cat line.sh
#!/bin/bash
filename=$1
count=0
while read a
do
let count++
echo " $count $a "
done < $filename
echo -e "\n Total $count lines read"

[saikrishna.b@gai-1339 Documents]$ sh line.sh testfile
 1 This is a sample script.
 2 To test
 3 the file is read line by line.
 4 Hope this works.
 5 Lets c.
 6 Done

 Total 6 lines read

No comments: