如何在 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
How do I get the last non-empty line of a file using tail in Bash?
提问by Debugger
How do I get the last non-empty line using tail
under Bash shell?
如何tail
在 Bash shell 下使用最后一个非空行?
For example, my_file.txt
looks like this:
例如,my_file.txt
看起来像这样:
hello
hola
bonjour
(empty line)
(empty line)
你好
hola
bonjour
(空行)
(空行)
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?
显然,如果我这样做,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 grep
to filter out the blank lines first?
如何使用grep
先过滤掉空行?
tail -r | grep -m 1 '.'
回答by kalu
Instead of tac
you can use tail -r
if 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 -r
isn'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:]
在某些情况下使用可能会更好。甚至没有覆盖所有空间,请参见此处。