'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 1:[1]

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

tac FILE |egrep -m 1 .

Solution 2:[2]

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

$ cat rjh
1
2
3


$ grep "." rjh | tail -1
3

Solution 3:[3]

Instead of tac you can use tail -r if available.

tail -r | grep -m 1 '.'

Solution 4:[4]

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

Solution 5:[5]

If tail -r isn't available and you don't have egrep, the following works nicely:

tac $FILE | grep -m 1 '.'

As you can see, it's a combination of two of the previous answers.

Solution 6:[6]

I had problems using other solutions, so I made this.

First, get last 25 lines, assuming at least 1 is not empty. Filter out empty lines, and print out the last line.

 tail -n25 file.txt | grep -v "^.$" | tail -n 1

One major advantage this has, you can show more than 1 line, just by changing the last 1 to, lets say, 5. Also, it only reads last 25 lines of the file.

If you have huge amounts of empty lines, you might want to change the 25 to something bigger, repeating until it works.

Solution 7:[7]

Print the last non-empty line that does not contain only tabs and spaces like this:

tac my_file.txt | grep -m 1 '[^[:blank:]]'

Note that Grep supports POSIX character class [:blank:] even if it is not documented in its manual page until 2020-01-01.

File may contain other non-visible characters, so maybe using [:space:] may be better in some cases. All space is not covered even by that, see here.

Solution 8:[8]

Using ag way:

cat file.txt | ag "\S" | tail -1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jürgen Hötzel
Solution 2 Andreas Louv
Solution 3 kalu
Solution 4 ghostdog74
Solution 5 Andy Forceno
Solution 6
Solution 7
Solution 8 pupsozeyde