Replacing all values from 4 columns in "|" seperated file using AWK in unix

Viewed 46

I have a | separated file and want to replace columns 2, 4, 6, 7 dates from 20200929 to 20201007.

File: e.lst

1|20200929|mni|20200929|pqr|20200929|20200929
2|20200929|mni|20200929|abc|20200929|20200929
3|20200929|mni|20200929|lmn|20200929|20200929
4|20200929|mni|20200929|stu|20200929|20200929

Command I tried is working for 2 columns.

awk -F\| '{OFS=FS}$2=20201007, $4=20201007 {print}' e.lst > ne.lst

But the same command when I add more columns to it, it gives a syntax error.

awk -F\| '{OFS=FS}$2=20201007, $4=20201007, $6=20201007 {print}' e.lst > ne.lst
                                          ^syntax error
2 Answers

You may use this awk to assign same value to multiple columns in a single expression:

awk 'BEGIN {FS=OFS="|"} { $2=$4=$6=$7=20201007 } 1' e.lst > ne.lst

1|20201007|mni|20201007|pqr|20201007|20201007
2|20201007|mni|20201007|abc|20201007|20201007
3|20201007|mni|20201007|lmn|20201007|20201007
4|20201007|mni|20201007|stu|20201007|20201007

Could you please try following. Have created an awk variable new which has your new date value, so we need not to change code inside, tomorrow you want to change it to a new value then change it here itself.

awk -v new="20201007" 'BEGIN{FS=OFS="|"} {$2=$4=$6=$7=new} 1' Input_file

Why OP's code didn't work: awk works on logic of condition then action, since OP wants to simply assign values to fields there is NO scope of condition here(until/unless OP don't want to hard code the field values), so OP is trying to assign values to fields but NOT in correct manner. It should be inside {.......} and it should be separated by equal to NOT by ,. Hence it would become like {$2=$4=$6=$7=your new value}

Related