Count blank fields in every line

Hello All,

I am trying a one liner for finding the number of null columns in every line of my flat file.

The format of my flat file is like this

a|b|c|d||||e|f|g|
a|b|c|d||||e|f|g|

I want to count the number of fields delimited by "|" which are blank.
In above case the count should be 3

The command tried by me is

cat filename | awk -F"|" '{print NF}'| head -1`

The is just giving me the count of all fields.

Please help me doing this

try..

 
awk -F"|" '{for(i=0;i<=NF;i++){if(!$i){C++}};print C;C=0}' filename

Thanks Vidyadhar,

I tried you solution and it works like a charm :slight_smile:

I tried getting the count for first line only

cat filename | awk -F"|" '{for(i=0;i<=NF;i++){if(!$i){C++}};print C;C=0}' | head -1

This works exactly as it should be.

Now, How do I get the count for a specific line number in a file.
Is there anyway we can do this.

Thanks

yes you can.. say you want to check it for line number 20

 
awk -F"|" 'NR==20{for(i=0;i<=NF;i++){if(!$i){C++}};print (C-1);C=0}' filename

I guess you might wanna make it C-1

Hello Vidyadhar,

I tried this one, This one is giving me count 1 less then the the previous command posted by you.
Previous command was working fine and showing me right number of blank fields

Also can you please let me know, what C-1 indicates here

never mind please use it ac C and not C-1 :slight_smile:

Thanks Vidyadhar