Update.
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 order. NF before the {} block does the job when the string is not empty. In this case, it prints the last field ( NF stands for the number of fields, so $NF is the last), and then it completes.
Test
$ 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 as it was. Finally, in END{} type the last saved word.
If you want to do this with sed , you can use this, which works if there are no empty lines at the end:
sed -n '${s/.* //; p}' a.txt
Explanation
$ denotes the last line of the file. In this case, do what is inside {} .s/.* //; p s/.* //; p delete everything to the last space. Then type p .
source share