Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

tail

line

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?

like image 453
Debugger Avatar asked Apr 14 '10 15:04

Debugger


People also ask

How do you find the last line of a file?

tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

How does tail work in bash?

Use of Tail CommandBy default, the 'tail' command reads the last 10 lines of the file. If you want to read more or less than 10 lines from the ending of the file then you have to use the '-n' option with the 'tail' command.

How do I echo an empty line in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.


1 Answers

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

tac FILE |egrep -m 1 . 
like image 100
Jürgen Hötzel Avatar answered Sep 20 '22 18:09

Jürgen Hötzel