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?
You can use Awk:
awk '/./{line=$0} END{print line}' my_file.txt
This solution has the advantage of using just one tool.
Use tac, so you dont have to read the whole file:
tac FILE |egrep -m 1 .
How about using grep to filter out the blank lines first?
$ cat rjh
1
2
3
$ grep "." rjh | tail -1
3
Instead of tac you can use tail -r if available.
tail -r | grep -m 1 '.'
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
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.
Print the last visually non-empty line:
tac my_file.txt | grep -vm 1 '^[[:space:]]*$'
or
awk 'BEGIN{RS="\r?\n[[:space:]]*"}END{print}' my_file.txt
The \r? is probably needed for DOS/Windows text files.
Character classes such as [:space:] work with GNU versions of awk (i.e. gawk) and grep at least. With some other implementations you have to enumerate space characters manually in the code i.e. replace [:space:] by \t \n\f\r\v. I do not know what would be the proper way to deal with backspace characters (\b) in the file.
The following works only with [:space:]:
tac my_file.txt | grep -m 1 '[^[:space:]]'
来源:https://stackoverflow.com/questions/2638912/how-do-i-get-the-last-non-empty-line-of-a-file-using-tail-in-bash