I want to extract last word of a file say a.txt in bash/sed/awk.
How can I do it?
To get to get the last word in the last line:
awk 'END {print $NF}' file
Updated.
If you want to use awk and make sure there is a word, use this:
tac a.txt | awk 'NF{print $NF; exit}'
tac prints the file in reverse. NF in front of the {} block makes it work whenever the line is not empty. In such case, it prints the last field (NF stands for number of fields, so $NF is the last one), and then exits.
$ cat a
hello my name
is blabla
and this is
my comment.
<--- note an empty line
$ tac a | awk 'NF{print $NF; exit}'
comment.
Or also, as suggested by Kent:
awk '{w=NF?$NF:w} END{print w}' file
w=$NF?$NF:w. This is a ternary operator: if NF>0 (no empty line), set w to the last field. Otherwise, keep it the way it was. Finally, in END{}, print the last saved word.
In case you want to make it with sed, you can use this, that works in case there is no empty lines at the end:
sed -n '${s/.* //; p}' a.txt
$ stands for last line of the file. In that case, do what is inside {}.s/.* //; p remove everything up to last space. Then print p.Try this awk command also,
awk -v RS="\0" '{print $NF}' file
RS="\0" turns all the records in a file to a single single record. And then {print $NF} prints the last field of that single record.
You can also use sed command ,
$sed -nr '${s/.* (.*)$/\1/pg}' File_name
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