Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite last field in last line using awk

Tags:

awk

I would like to overwrite the last field (2 fields in total) of the last line of a file with the value -9. I am using this command:

awk 'END{$2=-9}1' file.txt > new_file.txt

but it doesn't seem to work (no replacement is done). Why's that? Any ideas?

Thanks!

like image 777
Yorgos Avatar asked Dec 08 '25 09:12

Yorgos


1 Answers

You'll need to print the previous line, and then you can manipulate the last line in the END block before it has already been printed:

awk 'NR > 1 {print prev} {prev = $0} END {$2=-9; print}'
like image 57
glenn jackman Avatar answered Dec 11 '25 22:12

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!