如何反转文本文件的行?
我正在编写一个小型 shell 脚本,需要反转文本文件的行。 是否有标准的过滤器命令可以执行此类操作?
我的具体应用是,我正在获取 Git 提交标识符的列表,并且我想以相反的顺序处理它们:
git log --pretty=oneline work...master | grep -v DEBUG: | cut -d' ' -f1 | reverse
我想出的最好的方法是像这样实现 reverse
:
... | cat -b | sort -rn | cut -f2-
这使用cat
对每一行进行编号,然后 sort
按降序数字顺序对它们进行排序(最终反转整个文件),然后 cut
删除不需要的行号。
上面的方法适用于我的应用程序,但在一般情况下可能会失败,因为 cat -b
仅对非空行进行编号。
有没有更好、更通用的方法来做到这一点?
I'm writing a small shell script that needs to reverse the lines of a text file. Is there a standard filter command to do this sort of thing?
My specific application is that I'm getting a list of Git commit identifiers, and I want to process them in reverse order:
git log --pretty=oneline work...master | grep -v DEBUG: | cut -d' ' -f1 | reverse
The best I've come up with is to implement reverse
like this:
... | cat -b | sort -rn | cut -f2-
This uses cat
to number every line, then sort
to sort them in descending numeric order (which ends up reversing the whole file), then cut
to remove the unneeded line number.
The above works for my application, but may fail in the general case because cat -b
only numbers nonblank lines.
Is there a better, more general way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
在 GNU coreutils 中,有 tac(1)
In GNU coreutils, there's tac(1)
有一个命令可以满足您的目的:
-r
标志是非标准的,可能无法在所有系统上工作,但可以在 macOS 等系统上工作。There is a command for your purpose:
-r
flag is non-standard, may not work on all systems, works e.g. on macOS.答案不是 42,而是
tac
。编辑:使用
sed
速度较慢但消耗更多内存,甚至更长
Answer is not 42 but
tac
.Edit: Slower but more memory consuming using
sed
and even longer
与上面的 sed 示例类似,使用 perl - 也许更容易记住(取决于你的大脑如何连接):
Similar to the sed example above, using perl - maybe more memorable (depending on how your brain is wired):
如果这是您想要避免的唯一问题,那么为什么不使用“cat -n”对所有行进行编号呢?
If that's the only issue you want to avoid, then why not use "cat -n" to number all the lines?
在这种情况下,只需使用
--reverse
:In this case, just use
--reverse
:对我来说就像一个魅力......
Works like a charm for me...
比
sed
更快,并且兼容 openwrt 等嵌入式设备。More faster than
sed
and compatible for embed devices like openwrt.你甚至可以这样做:
You can even do this: