Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract last word of a file in bash/sed/awk

Tags:

file

bash

sed

awk

I want to extract last word of a file say a.txt in bash/sed/awk.

How can I do it?

like image 827
Wamiq Avatar asked Jun 11 '14 09:06

Wamiq


4 Answers

To get to get the last word in the last line:

awk 'END {print $NF}' file
like image 156
Jotne Avatar answered Nov 12 '22 13:11

Jotne


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.

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 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

Explanation

  • $ 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.
like image 35
fedorqui 'SO stop harming' Avatar answered Nov 12 '22 14:11

fedorqui 'SO stop harming'


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.

like image 1
Avinash Raj Avatar answered Nov 12 '22 15:11

Avinash Raj


You can also use sed command ,

$sed -nr '${s/.* (.*)$/\1/pg}' File_name
like image 1
Kalanidhi Avatar answered Nov 12 '22 13:11

Kalanidhi