Yishu Fang
Yishu Fang

Reputation: 9958

How to find out the number of fields in a certain line using awk?

How to find out the number of fields in a certain line using awk, and if there is only one field, I want to add something to the end of that line?

$ cat myFile
0: stackoverflow com
1: w3 org
2:
3: wikipedia org
4: 

I want the output like this:

$ cat myFile
0: stackoverflow com
1: w3 org
2: NULL
3: wikipedia org
4: NULL

Upvotes: 0

Views: 263

Answers (4)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

A sed answer (I know I'm off-topic):

sed 's/^\([[:digit:]]\+:\)[[:space:]]*$/& NULL/g' myFile

A bash answer (still off-topic):

while read -a a; do
    if [[ -z "${a[1]}" ]]; then
        echo "$a NULL"
    else
        echo "${a[@]}"
    fi
done < myFile

There's more than one way to skin a cat!

Upvotes: 1

shellter
shellter

Reputation: 37268

$ awk '{if (NF==0){print "NULL"}else print $0}' /tmp/myFile
stackoverflow com
w3 org
NULL
wikipedia org
NULL

NF is the awk special variable meaning Number(of)Fields. This would be the NumberOfFields that have values in them. You can change the value compared to NF==1 if your data really has numbered lines. I had assumed this was an artifact of using a numbering utility or editor.

The else statement means "any record with NOT zero # of fields, and as such will print records with 1 or more fields.

IHTH

Upvotes: 1

Kent
Kent

Reputation: 195049

 awk  'BEGIN{FS=OFS=":"}!$2{$2=" NULL"}1' file

test:

kent$  cat test.txt 
0: stackoverflow com
1: w3 org
2:
3: wikipedia org
4:


kent$  awk  'BEGIN{FS=OFS=":"}!$2{$2=" NULL"}1' test.txt
0: stackoverflow com
1: w3 org
2: NULL
3: wikipedia org
4: NULL

Upvotes: 1

Steve
Steve

Reputation: 54392

Add a test for the number of fields:

awk 'NF==1 { print $0, "NULL"; next }1' file

Results:

0: stackoverflow com
1: w3 org
2: NULL
3: wikipedia org
4: NULL

Upvotes: 4

Related Questions