Replace last field on last line with awk

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

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

      

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

Thank!

+3


source to share


3 answers


You will 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}'

      

+4


source


the END section is executed AFTER the last line has been processed, so you assign a $2

value after printing the last line.

There is also no guarantee that $ 2 or $ 0 or any of the fields will be stored in the END section (POSIX does not specify it), but IF in your awk, $ 2, etc. Is saved, then you need something like:

awk '
NR>1{print prev}
{prev=$0}
END {$2=-9; print}
'

      



If it doesn't, you need to create $ 0 first:

awk '
NR>1{print prev}
{prev=$0}
END {$0=prev; $2=-9; print}
'

      

+3


source


Another way: tac

+ awk

:

tac file.txt|awk 'NR==1{$NF="-9";}1'|tac >new_file.txt

      

PS : I prefer @glenn's solution.

+2


source







All Articles