Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK: replace and write a column value in the input file

Tags:

awk

I am trying to replace the $3 column values of the input file if $3 is > 100. I tried:

awk 'BEGIN {FS="\t"} {if($3 > 100) $3=$3/100;print}' test.stat

This outputs the correct changes to the stdout but, I need the change to write to the input file (test.stat) such that, the values of the remaining fields/records remain unchanged. Any suggestion?

Thanks. Another issue has arisen. I have a "counter" variable whose sum needs to be printed in the END block, I tried:

awk 'BEGIN {FS="\t",counter=0} 
{if($3 > 100) $3=$3/100;print else counter++}
END{print counter}' test.stat > ...

Now, only the counter value gets written to the file and not the $3 values. How can I separate the two outputs so one modifies the file and the other saved as bash variable using read command. Thanks.

like image 472
Shuvo Shams Avatar asked Mar 14 '12 16:03

Shuvo Shams


2 Answers

Awk isn't designed to edit things in-place. It's designed to process data and write it to stdout (or another file). You can do something like this:

$ awk 'BEGIN {FS="\t"} {if($3 > 100) $3=$3/100;print}' test.stat > test.stat.new \
    && mv test.stat test.stat.old && mv test.stat.new test.stat
like image 160
Andrew Beals Avatar answered Oct 18 '22 14:10

Andrew Beals


awk 'BEGIN {FS="\t"} {if($3 > 100) $3=$3/100;print}' test.stat > /tmp/tmp.stat && mv /tmp/tmp.stat test.stat

this should work

like image 23
Kent Avatar answered Oct 18 '22 14:10

Kent