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

Debugger picture Debugger · Apr 14, 2010 · Viewed 48.3k times · Source

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?

Answer

Jürgen Hötzel picture Jürgen Hötzel · Apr 14, 2010

Use tac, so you dont have to read the whole file:

tac FILE |egrep -m 1 .