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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With