views:

130

answers:

4

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?

+4  A: 

How about using grep to filter out the blank lines first?

$ cat rjh
1
2
3


$ cat rjh | grep "." | tail -1
3
RichieHindle
or, instead of 'cat rjh | grep "." | tail -1', use 'grep . rjh | tail -1'
amertune
`grep "."` technic is very useful, thanks
+3  A: 

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

tac FILE |egrep -m 1 .
Jürgen Hötzel
+1 for being concise
Michał Trybus
+1  A: 

You can use Awk:

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

This solution has the advantage of using just one tool.

Hai Vu
Downside: Needs to read the WHOLE file, and assign EACH LINE to awk variables -> This can be quite CPU and IO intensive.
Jürgen Hötzel
Yes, the solution is simple, but far from being efficient. An efficient solution would open the file, seek to the end and scan backward.
Hai Vu
+1  A: 

if you want to omit any whitespaces, ie, spaces/tabs at the end of the line, not just empty lines

awk 'NF{p=$0}END{print p}' file
ghostdog74