grep 倒数第二行
就像标题所说,如何使用 grep (或类似的 bash 工具)过滤(可变长度)文件的最后一行之前的行?
也就是说,显示除倒数第二行之外的所有内容。
谢谢
Like the title says, how can I filter with grep (or similar bash tool) the line-before-the-last-line of a (variable length) file?
That is, show everything EXCEPT the penultimate line.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
head
和tail
的组合,例如:来自 coreutils head 文档:
因此,
head -n -2
部分会删除其输入中除最后两行之外的所有内容。不幸的是,这不是便携式的。 (POSIX 不允许在
-n
参数中使用负值。)You can use a combination of
head
andtail
like this for example:From the coreutils head documentation:
So the
head -n -2
part strips all but the last two lines of its input.This is unfortunately not portable. (POSIX does not allow negative values in the
-n
parameter.)grep 是错误的工具。你可以用
Bash 之类的东西来实现它,它有内置的算术运算符,它比
expr
更优雅;但是expr
可以移植到其他 shell。您也可以在纯 sed 中执行此操作,但我不想考虑它。在 Perl 或 awk 中,很容易打印前一行,然后在 EOF 处打印最后一行。
编辑:毕竟我想到了
sed
。更详细;除非我们在最后一行 (
$
),否则交换模式空间和保持空间(记住当前行;检索上一行,如果有的话)。然后,除非这是第一行,否则打印模式空间中现在的任何内容(前一行,除非我们在最后一行)。grep
is the wrong tool for this. You can wing it with something likeBash has built-in arithmetic operators which are more elegant than
expr
; butexpr
is portable to other shells.You could also do this in pure
sed
but I don't want to think about it. In Perl or awk, it would be easy to print the previous line and then at EOF print the final line.Edit: I thought about
sed
after all.In more detail; unless we are at the last line (
$
), exchange the pattern space and the hold space (remember the current line; retrieve the previous line, if any). Then, unless this is the first line, print whatever is now in the pattern space (the previous line, except when we are on the last line).awk oneliner:(使用 seq 10 进行测试):
awk oneliner: (test with seq 10):
使用
ed
:Using
ed
: