如何在 Bash 中使用 tail 获取文件的最后一个非空行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2638912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:10:56  来源:igfitidea点击:

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

bashlinetail

提问by Debugger

How do I get the last non-empty line using tailunder Bash shell?

如何tail在 Bash shell 下使用最后一个非空行?

For example, my_file.txtlooks like this:

例如,my_file.txt看起来像这样:

hello
hola
bonjour
(empty line)
(empty line)

你好
hola
bonjour
(空行)
(空行)

Obviously, if I do tail -n 1 my_file.txtI will get an empty line. In my case I want to get bonjour. How do I do that?

显然,如果我这样做,tail -n 1 my_file.txt我会得到一个空行。就我而言,我想得到bonjour. 我怎么做?

采纳答案by Hai Vu

You can use Awk:

您可以使用 awk:

awk '/./{line=
tac FILE |egrep -m 1 .
} END{print line}' my_file.txt

This solution has the advantage of using just one tool.

此解决方案的优点是仅使用一种工具。

回答by Jürgen H?tzel

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

使用 tac,因此您不必阅读整个文件:

$ cat rjh
1
2
3


$ grep "." rjh | tail -1
3

回答by RichieHindle

How about using grepto filter out the blank lines first?

如何使用grep先过滤掉空行?

tail -r | grep -m 1 '.'

回答by kalu

Instead of tacyou can use tail -rif available.

如果可用,tac您可以使用代替tail -r

awk 'NF{p=
tac my_file.txt | grep -m 1 '[^[:blank:]]'
}END{print p}' file

回答by ghostdog74

if you want to omit any whitespaces, ie, spaces/tabs at the end of the line, not just empty lines

如果您想省略任何空格,即行尾的空格/制表符,而不仅仅是空行

##代码##

回答by Andy Forceno

If tail -risn't available and you don't have egrep, the following works nicely:

如果tail -r不可用而您没有egrep,则以下操作很好:

tac $FILE | grep -m 1 '.'

tac $FILE | grep -m 1 '.'

As you can see, it's a combination of two of the previous answers.

如您所见,它是前面两个答案的组合。

回答by jarno

Print the last non-empty line that does not contain only tabs and spaces like this:

打印不只包含制表符和空格的最后一个非空行,如下所示:

##代码##

Note that Grep supports POSIX character class [:blank:]even if it is not documented in its manual page until 2020-01-01.

请注意,Grep 支持 POSIX 字符类,[:blank:]即使直到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.

文件可能包含其他不可见的字符,因此[:space:]在某些情况下使用可能会更好。甚至没有覆盖所有空间,请参见此处