Reputation: 51
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!
Upvotes: 3
Views: 547
Reputation: 14955
Another way using tac
+ awk
:
tac file.txt|awk 'NR==1{$NF="-9";}1'|tac >new_file.txt
PS: I prefer @glenn solution.
Upvotes: 2
Reputation: 203899
the END section is executed AFTER processing the last line so you're assigning $2
a value after the last line has been printed.
There's also no guarantee that $2 or $0 or any of the fields will be preserved in the END section (POSIX doesn't specify it) but IF in your awk, $2, etc ARE preserved then what you need is something like:
awk '
NR>1{print prev}
{prev=$0}
END {$2=-9; print}
'
If they aren't then you need to create a $0 first:
awk '
NR>1{print prev}
{prev=$0}
END {$0=prev; $2=-9; print}
'
Upvotes: 3
Reputation: 247002
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}'
Upvotes: 4