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

因此,从以下内容开始:

foo
bar
baz

我希望最后

baz
bar
foo

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


当前回答

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

其他回答

编辑下面生成从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

BSD尾部:

tail -r myfile.txt

参考:FreeBSD、NetBSD、OpenBSD和OS X手册页。

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

如果要就地修改文件,可以运行

sed -i '1!G;h;$!d' filename

这样就不需要创建临时文件,然后删除或重命名原始文件,并具有相同的结果。例如:

$tac file > file2
$sed -i '1!G;h;$!d' file
$diff file file2
$

根据埃菲米恩特的回答,这几乎做到了,但不是完全做到了我想要的。