我想反转文本文件(或stdin)中的行顺序,保留每行的内容。

因此,从以下内容开始:

foo
bar
baz

我希望最后

baz
bar
foo

是否有用于此的标准UNIX命令行实用程序?


当前回答

编辑下面生成从1到10的随机排序的数字列表:

seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') **...**

其中点被替换为实际命令,该命令反转列表

tac

seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') \
<(tac)

python:在sys.stdin上使用[::-1]

seq 1 10 | sort -R | tee /tmp/lst |cat <(cat /tmp/lst) <(echo '-------') \
<(python -c "import sys; print(''.join(([line for line in sys.stdin])[::-1]))")

其他回答

tac <file_name>

例子:

$ cat file1.txt
1
2
3
4
5

$ tac file1.txt
5
4
3
2
1

对于可能在shell脚本中使用tac的跨操作系统(即OSX、Linux)解决方案,如上文所述,使用自制程序,然后将tac别名如下:

安装lib

对于MacOS

brew install coreutils

对于linux debian

sudo apt-get update
sudo apt-get install coreutils 

然后添加别名

echo "alias tac='gtac'" >> ~/.bash_aliases (or wherever you load aliases)
source ~/.bash_aliases
tac myfile.txt

以下是著名的sed技巧:

# reverse order of lines (emulates "tac")
# bug/feature in HHsed v1.5 causes blank lines to be deleted
sed '1!G;h;$!d'               # method 1
sed -n '1!G;h;$p'             # method 2

(说明:在保留缓冲区、交换缓冲区和保留缓冲区之前准备非初始行,在末尾打印输出行)

或者(以更快的执行速度)从awk一行代码:

awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*

如果你记不住了,

perl -e 'print reverse <>'

在具有GNU实用程序的系统上,其他答案更简单,但并不是所有的世界都是GNU/Linux。。。

$ (tac 2> /dev/null || tail -r)

试试tac,它在Linux上运行,如果不起作用,可以使用tail-r,它在BSD和OSX上运行。

您可以在命令行上使用Perl:

perl-e'my@b=();而(<>){push(@b,$_);};打印联接(“”,反向(@b));'原始>版本