Reputation: 1364
I want to extract last word of a file say a.txt
in bash/sed/awk.
How can I do it?
Upvotes: 7
Views: 23403
Reputation: 2122
sed -n '/^$/!{$ s/.* \(\w*\)$/\1/p}'
This will omit blank lines and print the last word on the last non-blank line.
Upvotes: 0
Reputation: 58371
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
Upvotes: 0
Reputation: 20980
sed
variant to support empty last line (if any):
sed -n '/[^ ]/h; ${g;s/ *$//; s/.* //p}' a.txt
Upvotes: 0
Reputation: 47099
You can also get the last word with grep
and tail
:
<a.txt grep -o '\w\+' | tail -n1
Upvotes: 0
Reputation: 289535
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
.Upvotes: 6
Reputation: 5092
You can also use sed command ,
$sed -nr '${s/.* (.*)$/\1/pg}' File_name
Upvotes: 1
Reputation: 174696
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.
Upvotes: 1
Reputation: 41456
To get to get the last word in the last line:
awk 'END {print $NF}' file
Upvotes: 21