Insert string 'NULL' where there is a null value

I have an input file having 7 fields delimited by ,
eg :

1,ABC,hg,1,2,34,3
2,hj,YU,2,3,4,
3,JU,kl,4,5,7,
4,JK,KJ,3,56,4,5

The seventh field here in some lines is empty, whereas the other lines there is a value.
How do I insert string NULL at this location (7th loc) for these lines where output will look like

1,ABC,hg,1,2,34,3
2,hj,YU,2,3,4,NULL
3,JU,kl,4,5,7,NULL
4,JK,KJ,3,56,4,5

One way:

awk -F, '!$7{$7="NULL"}1' OFS="," file
1 Like

Hello Franklin,

could you explain the meaning of the number "one"?
I suppose that is for printing the line...but which is the meaning exactly?

thank you

for the last column:

sed 's/,$/,NULL/g' file

to insert a "NULL" in every empty column:

sed -e 's/,,/,NULL,/g' -e 's/,$/,NULL/g' file

wow, the sed works great. Exactly what i wanted. I was stuck with 's/$\x0/NULL/g' and was wondering what was the mistake. Well thank you very much funksen

Hi,

The 1 is a condition without any action. It matches when its value is nonzero (if a number) or non-null (if a string).
If it's true awk prints the current record, similar to {print}.

Regards

How do we get to know whether its true or not? is there any dependency with the previous command/expression written just before "1" ?

A "0" in the final field would be replaced by "NULL". If that's not desirable, to prevent this, force $7 to a string type by concatenating with a null string before the resulting string's value is evaluated in a boolean context:

awk -F, '!($7""){$7="NULL"}1' OFS=","

Regards,
Alister

Hi Alister,

Thanks for mention this (to me for the 2nd time :)).

Regards