我想反转文本文件(或stdin)中的行顺序,保留每行的内容。
因此,从以下内容开始:
foo
bar
baz
我希望最后
baz
bar
foo
是否有用于此的标准UNIX命令行实用程序?
我想反转文本文件(或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]))")
其他回答
最佳解决方案:
tail -n20 file.txt | tac
最简单的方法是使用tac命令。tac是猫的逆。例子:
$ cat order.txt
roger shah
armin van buuren
fpga vhdl arduino c++ java gridgain
$ tac order.txt > inverted_file.txt
$ cat inverted_file.txt
fpga vhdl arduino c++ java gridgain
armin van buuren
roger shah
我真的很喜欢“尾巴-r”的答案,但我最喜欢的呆呆的答案是。。。。
gawk '{ L[n++] = $0 }
END { while(n--)
print L[n] }' file
以下是著名的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。。。
对于可能在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