Thursday, 5 May 2016

Read file line by line and count no. of lines using Shell script

Guys, in today's post we'll see how to parse a file line by line and count the number of lines in it.

We will simply use redirection to read the file. Note that we will pass the filename as a runtime parameter to the script.

Alright here we go. Suppose I have a file TextFile1.txt with the following contents. I want to print the total number of lines in it.

ABCD
DEFG
GHI
JKL
MNO
PQR
STU

VWXYZ

Now, here's the script part.

#!/bin/bash
#Sript to count number of lines in a file

File=$1

count=0

while read LINE

do

let count++

echo "$count $LINE"

done < $File


echo -e "Total $count Lines read\n"

Here's the output :

1 ABCD
2 DEFG
3 GHI
4 JKL
5 MNO
6 PQR
7 STU
8 VWXYZ

Total 8 Lines read

Cheers it has correctly displayed the count of lines in the file. In case of any questions/doubts, kindly leave your comments.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker