Wamiq
Wamiq

Reputation: 1364

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

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

Answers (9)

jgshawkey
jgshawkey

Reputation: 2122

 sed -n '/^$/!{$ s/.* \(\w*\)$/\1/p}'

This will omit blank lines and print the last word on the last non-blank line.

  • /^$/! find non-blank lines
  • $ s/ on the last line substitute
  • .* (\w*)$ capture anything between the ()
  • \1 substitute line for capture group ()
  • p print it

Upvotes: 0

potong
potong

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

anishsane
anishsane

Reputation: 20980

sed variant to support empty last line (if any):

sed -n '/[^ ]/h; ${g;s/ *$//; s/.* //p}' a.txt

Upvotes: 0

rpax
rpax

Reputation: 4496

Using tail and grep :

tail -1 myFile.txt | grep -oE '[^ ]+$'

Upvotes: 1

Thor
Thor

Reputation: 47099

You can also get the last word with grep and tail:

<a.txt grep -o '\w\+' | tail -n1

Upvotes: 0

fedorqui
fedorqui

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.

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.

Upvotes: 6

Kalanidhi
Kalanidhi

Reputation: 5092

You can also use sed command ,

$sed -nr '${s/.* (.*)$/\1/pg}' File_name

Upvotes: 1

Avinash Raj
Avinash Raj

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

Jotne
Jotne

Reputation: 41456

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

awk 'END {print $NF}' file

Upvotes: 21

Related Questions