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

混江龙づ霸主 提交于 2019-11-30 03:14:08

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 .
RichieHindle

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:]]'
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!