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

╄→гoц情女王★ 提交于 2019-11-28 20:54:24

问题


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?


回答1:


You can use Awk:

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

This solution has the advantage of using just one tool.




回答2:


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

tac FILE |egrep -m 1 .



回答3:


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

$ cat rjh
1
2
3


$ grep "." rjh | tail -1
3



回答4:


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

tail -r | grep -m 1 '.'



回答5:


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



回答6:


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.




回答7:


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

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