Search code examples
bashlinetail

How do I get the last non-empty line of a file using tail in Bash?


How do I get the last non-empty line using tail under Bash shell?

For example, my_file.txt looks like this:

hello
hola
bonjour
(empty line)
(empty line)

Obviously, if I do tail -n 1 my_file.txt I will get an empty line. In my case I want to get bonjour. How do I do that?


Solution

  • You can use Awk:

    awk '/./{line=$0} END{print line}' my_file.txt
    

    This solution has the advantage of using just one tool.