How to reverse lines of a text file?

2020-02-27 01:53发布

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?

9条回答
乱世女痞
2楼-- · 2020-02-27 02:33
cat -b only numbers nonblank lines"


If that's the only issue you want to avoid, then why not use "cat -n" to number all the lines?

查看更多
走好不送
3楼-- · 2020-02-27 02:38

Similar to the sed example above, using perl - maybe more memorable (depending on how your brain is wired):

perl -e 'print reverse <>'
查看更多
狗以群分
4楼-- · 2020-02-27 02:38
rev <name of your text file.txt>

You can even do this:

echo <whatever you want to type>|rev
查看更多
登录 后发表回答