Debugger
Debugger

Reputation: 9498

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?

Upvotes: 40

Views: 57311

Answers (9)

pormulsys
pormulsys

Reputation: 21

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.

Upvotes: 2

ー PupSoZeyDe ー
ー PupSoZeyDe ー

Reputation: 1392

Using ag way:

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

Upvotes: 0

jarno
jarno

Reputation: 858

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.

Upvotes: 0

RichieHindle
RichieHindle

Reputation: 281875

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

$ cat rjh
1
2
3


$ grep "." rjh | tail -1
3

Upvotes: 26

philosophie
philosophie

Reputation: 304

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.

Upvotes: 2

kalu
kalu

Reputation: 61

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

tail -r | grep -m 1 '.'

Upvotes: 6

ghostdog74
ghostdog74

Reputation: 343141

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

Upvotes: 4

Hai Vu
Hai Vu

Reputation: 40783

You can use Awk:

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

This solution has the advantage of using just one tool.

Upvotes: 30

Jürgen Hötzel
Jürgen Hötzel

Reputation: 19757

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

tac FILE |egrep -m 1 .

Upvotes: 38

Related Questions