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

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

expected results

 echo $Last_word

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
bla ble bli$
$ tac file | awk 'NF{print $NF; exit}'

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.


Keep track of the last word of the last non-empty line and print it at the end:

awk '/\S/{ s=$NF; } END{ print(s); }'

No need to keep the whole file in memory to print its lines in reverse order or anything like that.

sed -n '$p' example.txt | awk '{print $NF}'

This will get the last line of the file and display the last column in the last line.

  • If last line is blank, nothing to print – ctac_ Jan 3 '18 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.