Linux – how to find the last word in file & ignore empty spaces

awklinuxperlsedtext processing

how to find the last word in file even after word there are empty lines

the case

I tried this to find the last word

tail -1  /tmp/requests.txt

but no output

I try the following approach

 awk 'END {print $NF}'   /tmp/requests.txt

but no output

I capture the word only by tail -6 ( because the word was 6 empty lines before the end of the file

 tail -6  /tmp/requests.txt
 "IN_PROGRESS"

so what is the way to capture the last word in case we have empty space or not

expected results

 echo $Last_word
 IN_PROGRESS

Best Answer

Just start reading from the bottom and print the last word of the first line containing at least "something":

tac file | awk 'NF{print $NF; exit}'

For example:

$ cat -vet file     # note the spaces and tabs
hello$
bla ble bli$
   $
^I$
$ tac file | awk 'NF{print $NF; exit}'
bli

If you happen to not have tac, just use the same logic when reading the file normally:

awk 'NF{last=$NF} END{print last}' file

That is, store the last word whenever there is "something" in a line. Finally, print the stored value.

Related Question