Page 1 of 1

Counting No Of Lines

Posted: Thu Jun 02, 2005 11:12 am
by pandu80
Hi ,
I would like count the no of lines in a text file.
Iam using the 'cat filename | wc -l' which returns the no of lines.
But Before that i need to eliminate the empty lines in the text file.
how can i achieve this?.
Any help would be appreciated.

TIA

Posted: Thu Jun 02, 2005 11:15 am
by amsh76
Where are these empty lines..you can use head, tail or sed commands in unix...for removing those extra records.

Posted: Thu Jun 02, 2005 11:40 am
by Sainath.Srinivasan
You can use grep to remove empty lines.

head and tail do not identify or remove empty lines.

Posted: Thu Jun 02, 2005 12:10 pm
by amsh76
Hi Sainath,

What i meant by head and tail is to move the data (w/o empty records) to another file..provided he knows the position of empty records.

Posted: Thu Jun 02, 2005 4:17 pm
by ray.wurlod
sed (stream editor) is probably the fastest mechanism for removing empty lines, then pipe the result through wc -l

Posted: Sun Jun 05, 2005 12:56 am
by SriKara
You can remove the emtpy lines from a file and then count by using the below command.

cat filename | grep -v "^$" | wc -l

Posted: Sun Jun 05, 2005 4:07 am
by Sainath.Srinivasan
You can reduce it saying

grep '^$' filename | wc -l

But make sure that an 'empty line' is a line 'with no value including blank spaces'. Otherwise your grep pattern will be different.

Posted: Sun Jun 05, 2005 4:29 am
by Prashantoncyber
Sainath,

Wht should be commands if there is Blank spaces in line and we dont want to count them as well?

thanks
Prashant

Posted: Sun Jun 05, 2005 6:02 am
by SriKara
To determine the number of lines with all spaces, the below command can be used.

cat filename | tr -s " " " " | grep '^ $' | wc -l

Dont know a better way to do this. Using tr command for a large file can by cumbersome though. Unix Gurus??

Posted: Sun Jun 05, 2005 7:21 am
by chulett
I would think sed would be a better answer. Takes all the normal regular expressions, so something like this perhaps?

Code: Select all

sed -e '/^$/d' -e '/^ *$/d' filename
Off the top of my head, this should remove blank lines and lines that only consist of spaces. Exact syntax may vary from UNIX to UNIX. Output would be to standard out, so it could be used in the Filter of the Sequential File stage.

Of course, pipe the output to wc if you just want to count the results.

Posted: Mon Jun 06, 2005 10:43 am
by Sainath.Srinivasan
Sed is good. You can also do the same with grep and make it work more efficient.