I want to extract last word of a file say a.txt in bash/sed/awk.
How can I do it?
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.awk 'END{print $NF}' file I said like because, the last line of the file could be empty. since you came first, you could do some fix and complete the answer.awk 'END{print $NF}' file won't always work.awk '{w=$NF?$NF:w}END{print w}' files/.* //; p is fine unless line end with a space. mya i suggests/.* \([[:space:]]\{1,\}[[:space:]]*$/\1/;p so event with line with 1 word (or not, but this depend on exact resquest) on last line it worksYou can also use sed command ,
$sed -nr '${s/.* (.*)$/\1/pg}' File_name p ouside the s/// or it will fail if there is not at least 2 word on last line and g is not needed in this case, there is only 1 end per line. Finaly, it failed on line with last position is a space character.This might work for you (GNU sed):
sed -r '/\w/{s/.*\W(\w+)\W*$/\1/;h};$!d;x;/./!d' file Saves the last word of the current line in the hold space then deletes the line. At the end of the file it retrieves the last word and prints it out unless there was no word in which case it deletes the empty line.
An alternative way is to slurp the whole file into memory:
sed -r ':a;$!{N;ba};s/.*\W(\w+)\W*$/\1/p;d' file