safwanpaloli
safwanpaloli

Reputation: 59

count the fields without empty line using awk command

safwanpaloli@hello:~/linx$ cat 1.txt 

Name    age address email
safwan  26  india   [email protected]
rashi   24  India   [email protected]
shanif  25  India   [email protected]
pradeep 25  India   [email protected]
safwanpaloli@hello:~/linx$ 

Display the line number with all file content

awk '{print NR,$0}'

output is

1 
2 Name  age address     email
3 safwan    26  india   [email protected]
4 rashi     24  India   [email protected]
5 shanif    25  India   [email protected]
6 pradeep   25  India   [email protected]

expected result is


1 Name  age address     email
2 safwan    26  india   [email protected]
3 rashi     24  India   [email protected]
4 shanif    25  India   [email protected]
5 pradeep   25  India   [email protected]

Upvotes: 0

Views: 429

Answers (2)

dan
dan

Reputation: 5231

This prints non empty lines, with their count. To be counted, the line must contain at least one non whitespace character.

awk '$1!="" {print ++c,$0}'

This is similar, but only completely empty lines are skipped. Eg. a line containing nothing but a single space would still get counted.

awk '/./ {print ++c,$0}'

You can also remove empty lines with one of these greps:

grep '[^[:space:]]'

grep .

Upvotes: 1

James Brown
James Brown

Reputation: 37404

You could examine if NF has a value greater than 0 and use a counter variable:

$ awk 'NF{print ++c,$0}' file

Output:

1 Name    age address email
2 safwan  26  india   [email protected]
...

If the first line is truly empty (ie. no space in there) you could use nl file. It will print the empty line but not number it.

Above nl functionality with awk (empty lines output but not numbered):

$ awk '{print (NF?++c:""),$0}' file

Output:


1 Name    age address email
2 safwan  26  india   [email protected]
3 rashi   24  India   [email protected]
...

Upvotes: 2

Related Questions