Extract last word of file in bash / sed / awk

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

How can i do this?

+6
source share
9 answers

To get the last word in the last line:

 awk 'END {print $NF}' file 
+14
source

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 .
+6
source

Try also this awk command,

 awk -v RS="\0" '{print $NF}' file 

RS="\0" turns all records into a file into one single record. And then {print $NF} prints the last field of this single record.

+1
source

You can also use the sed command,

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

Using tail and grep:

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

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

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

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

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

This may 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 on hold, and then deletes the line. At the end of the file, it extracts the last word and prints it, if there were no words, in this case it deletes the empty line.

An alternative way is to cut the entire file into memory:

 sed -r ':a;$!{N;ba};s/.*\W(\w+)\W*$/\1/p;d' file 
0
source
  sed -n '/^$/!{$ s/.* \(\w*\)$/\1/p}' 

This omits empty lines and prints the last word on the last non-empty line.

  • / ^ $ /! find non empty lines
  • $ s / on the last line substitute
  • . * (\ w *) $ grabs anything between ()
  • \ 1 substitution string for capture group ()
  • p print it
0
source

Source: https://habr.com/ru/post/970688/


All Articles