How to add missing value?

Hi Gurus,

I have a txt file. some record missed 2nd colum value, I need put default value into the file.
ex: below file, first 4 records, missed one column (only 4 columns. it should be 5)

 
$cat missedfield
aaa,bbb,ccc,fff
aaa,bbb,ccc,ddd
111,222,333,444
111,222,333,444
111,222,333,444,555

I tried awk command as below:
the problem is I want to if NF<5 and $NF>2, $2='xxx'(default value), then assign $2 to $3 and so on. but below code the column value is minused.

 
awk -F"," '{if (NF< 5 && $NF>2) {$2="XXX"}{ $NF=$NF-1} {print $0}}' missedfield

Can anybody help me this?

Thanks in advance.

That may be the most correct way but a quick way to get the same output is to just append the new value and the field separator inside of $1.

mute@tiny:~$ awk 'NF<5{$1=$1 FS "XXX"}1' FS=, OFS=, missedfield
aaa,XXX,bbb,ccc,fff
aaa,XXX,bbb,ccc,ddd
111,XXX,222,333,444
111,XXX,222,333,444
111,222,333,444,555

or iterating over the fields you'd have to first increase the field count and starting from the end work your way backwards moving them until $2 is now free to assign:

mute@tiny:~$ awk 'NF<5{NF++;for (i=NF;i>1;i--)$i=$(i-1);$2="XXX"}1' FS=, OFS=, missedfield
aaa,XXX,bbb,ccc,fff
aaa,XXX,bbb,ccc,ddd
111,XXX,222,333,444
111,XXX,222,333,444
111,222,333,444,555

the 1 at the end is shorthand for { print $0 } since the default action in awk is to print and 1 is always true.

1 Like

Hello Ken6503,

You haven't shown us the expected output, so I am not sure either we need to put both conditions of having number of fields lesser than 5 + $NF (last field's) value should be grater than 2. But by seeing your expression I have made following.

 awk -F, '{if(NF<5 && $NF+0 > 2){$2="XXX" OFS $2;print;next}} 1' OFS=,  Input_file
 

Output will be as follows.

aaa,bbb,ccc,fff
aaa,bbb,ccc,ddd
111,XXX,222,333,444
111,XXX,222,333,444
111,222,333,444,555
 

Thanks,
R. Singh

1 Like

Thanks R.Singh and neutronscott.

As always. the code you provided works perfect.

Thank you very much.

---------- Post updated at 01:16 PM ---------- Previous update was at 09:16 AM ----------

Below is file and result with R.Singh and neutronscott's code.

Please note: for R.Singh code, I don't fully understand

$NF+0 > 2

why here need $NF+0, I removed +0. the result are exactly I need.

[EMAIL="hankey@cbsccus291d:/apps/hankey$cat"]

 
$cat missedfield 
aaa,bbb,ccc
aaa,bbb,ccc,ddd
111,222,333,444
111,222,333,444
111,222,333,444,555
$nawk -F, '{if(NF<5 && $NF > 2){$2="XXX" OFS $2;print;next}} 1' OFS=,   missedfield
aaa,XXX,bbb,ccc
aaa,XXX,bbb,ccc,ddd
111,XXX,222,333,444
111,XXX,222,333,444
111,222,333,444,555
$nawk 'NF<5{$1=$1 FS "XXX"}1' FS=, OFS=, missedfield
aaa,XXX,bbb,ccc
aaa,XXX,bbb,ccc,ddd
111,XXX,222,333,444
111,XXX,222,333,444
111,222,333,444,555

[/EMAIL]