Replace with NA if blank is there

Hi All,

please help me below request.

i am having a file XXXX.dat. in Unix.

example-

plan_dk,imsmodelvar,paymt_type_az,mmars_plan,mmars_payer,mmars_pbm,account,botpbm,formulary_Crestor
0000000000,,3,MAIL ORDER,MAIL ORDER DATA,N/A,MAIL ORDER,N/A,
0000000000,6,,MAIL ORDER,MAIL ORDER DATA,N/A,MAIL ORDER,N/A,
0000000000,,,MAIL ORDER,MAIL ORDER DATA,N/A,MAIL ORDER,N/A,

in above lines 1st line is header (column names) and below are the values.
my requirement is --> if only 2nd and 3rd columns value are Null then it should replace with NA.Another columns value should not be changed keep as it is.
how to do in unix either command or a shell script.

Result should look like below mentioned.

0000000000,NA,3,MAIL ORDER,MAIL ORDER DATA,N/A,MAIL ORDER,N/A,
0000000000,6,NA,MAIL ORDER,MAIL ORDER DATA,N/A,MAIL ORDER,N/A,
0000000000,NA,NA,MAIL ORDER,MAIL ORDER DATA,N/A,MAIL ORDER,N/A,

Advance Thanks...

Thanks,
Krupa

Try:

awk -F, -vOFS=, '{$2=$2!=""?$2:"NA";$3=$3!=""?$3:"NA"}1' file.dat
1 Like

A solution 4 characters shorter than bartus11's:

awk -F, -vOFS=, '{$2=$2""?$2:"NA";$3=$3""?$3:"NA"}1' file.dat

This might not work with some old awk implementations.

1 Like

Thanks

it's working now

One char shorter than elixir_sinari's:

awk -F, -vOFS=, '!($2""){$2="NA"}!($3""){$3="NA"}1' file

or, even 2 chars less

awk -F, -vOFS=, '$2==""{$2="NA"}$3==""{$3="NA"}1' file
1 Like

How about this one?

awk '!$2{$2="n/a"}!$3{$3="n/a"}1' FS=, OFS=, file

Did I win the contest of who has the shortest? :slight_smile:

1 Like

A 0 (zero) shouldn't replaced by n/a IMHO.

1 Like
sed 's/\(^[^,]*\,.*\),,/\1,NA,/;s/\(^[^,]*\),,/\1,NA,/' infile

For any columns if empty, replace by NA

awk '{for (i=1;i<=NF-1;i++) if ($i=="") $i="NA"}1' FS=, OFS=,  infile

The request was to replace ONLY $2 and/or $3. If you really want ro replace all empty fields, try

 awk '{gsub(",,",",NA,")}1' file

In that case you would need to do that twice in this case, for example:

sed 's/,,/,NA,/; s/,,/,NA,/' file

--
There would be no need for that with perl:

perl -pe 's/,(?=,)/,NA/g' file

With Sed..

sed -e 's/^\([^,]*,\)\(,\)/\1NA\2/' -e 's/\([^,]*,[^,]*,\)\(,\)/\1NA\2/'  inputfile

Or a little shorter version..

sed -e 's/^\([^,]*,\),/\1NA,/' -e 's/\([^,]*,[^,]*,\),/\1NA,/' inputfile