如何反转文本文件的行? [英] How to reverse lines of a text file?

查看:28
本文介绍了如何反转文本文件的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个需要反转文本文件行的小型 shell 脚本.有没有标准的过滤命令来做这种事情?

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?

我的具体应用是我正在获取一个 Git 提交标识符列表,我想以相反的顺序处理它们:

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

我想出的最好的方法是像这样实现 reverse:

The best I've come up with is to implement reverse like this:

... | cat -b | sort -rn | cut -f2-

这使用 cat 为每一行编号,然后 sort 按数字降序对它们进行排序(最终反转整个文件),然后 cut 删除不需要的行号.

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.

以上适用于我的应用程序,但在一般情况下可能会失败,因为 cat -b 只对非空白行进行编号.

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?

推荐答案

GNU coreutils,还有 tac(1)

这篇关于如何反转文本文件的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆