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

因此,从以下内容开始:

foo
bar
baz

我希望最后

baz
bar
foo

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


当前回答

这将同时适用于BSD和GNU。

awk '{arr[i++]=$0} END {while (i>0) print arr[--i] }' filename

其他回答

Just Bash:)(4.0+)

function print_reversed {
    local lines i
    readarray -t lines

    for (( i = ${#lines[@]}; i--; )); do
        printf '%s\n' "${lines[i]}"
    done
}

print_reversed < file

tail-r适用于大多数Linux和MacOS系统

seq 1 20 |尾部-r

以下是著名的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。。。

如果你碰巧在vim使用

:g/^/m0
$ (tac 2> /dev/null || tail -r)

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