简体   繁体   English

在Bash中反转文本文件

[英]Reverse text file in Bash

How can I reverse a text file in Bash? 如何在Bash中反转文本文件?

For example, if some.txt contains this: 例如,如果some.txt包含以下内容:

book
pencil
ruler

then how can I get this? 那怎么能得到这个呢? :

relur
licnep
koob

Try the combined form of tac and rev commands, 尝试tacrev命令的组合形式,

$ tac file | rev
relur
licnep
koob

From man tac 来自man tac

tac - concatenate and print files in reverse tac - 反向连接和打印文件

From man rev 来自man rev

The rev utility copies the specified files to standard output, reversing the order of characters in every line. rev实用程序将指定的文件复制到标准输出,反转每行中的字符顺序。 If no files are specified, stan‐ dard input is read. 如果未指定文件,则读取标准输入。

Mac OS X uses FreeBSD sed that allows escaped newlines in its replacement string. Mac OS X使用FreeBSD sed ,允许在替换字符串中使用转义换行符。

The following version of the solution given by F. Hauri works for GNU sed 4.2.1 , FreeBSD sed and minised 1.15 . F. Hauri给出的以下版本的解决方案适用于GNU sed 4.2.1 ,FreeBSD sedminise 1.15

escnl='\
'

sed -ne '
    /../!b;
    s/^.*$/'"${escnl}"'&'"${escnl}"'/;
    tx;
  :x;
    s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/;
    tx;
    s/\n//g;
  :;
    1!G;
    $p;
    h
' <<<$'book\npencil\nruler'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM