How to reverse lines of a text file?

流过昼夜 提交于 2019-11-30 11:09:05

In GNU coreutils, there's tac(1)

There is a standard command for your purpose:

tail -r file.txt

prints the lines of file.txt in reverse order!

Answer is not 42 but tac.

Edit: Slower but more memory consuming using sed

sed 'x;1!H;$!d;x'

and even longer

perl -e'print reverse<>'
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?

:   "@(#)$Id: reverse.sh,v 1.2 1997/06/02 21:45:00 johnl Exp $"
#
#   Reverse the order of the lines in each file

awk ' { printf("%d:%s\n", NR, $0);}' $* |
sort -t: +0nr -1 |
sed 's/^[0-9][0-9]*://'

Works like a charm for me...

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

perl -e 'print reverse <>'

In this case, just use --reverse:

$ git log --reverse --pretty=oneline work...master | grep -v DEBUG: | cut -d' ' -f1
rev <name of your text file.txt>

You can even do this:

echo <whatever you want to type>|rev
awk '{a[i++]=$0}END{for(;i-->0;)print a[i]}'

More faster than sed and compatible for embed devices like openwrt.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!