How can I reverse a text file in Bash?
For example, if some.txt
contains this:
book
pencil
ruler
then how can I get this? :
relur
licnep
koob
Try the combined form of tac
and rev
commands,
$ tac file | rev
relur
licnep
koob
From man tac
tac - concatenate and print files in reverse
From man rev
The rev utility copies the specified files to standard output, reversing the order of characters in every line. If no files are specified, stan‐ dard input is read.
tac
: sed -n -e '1!G' -e '$p' -e h
or simplier: sed -ne '1!G;$p;h'
Nov 4, 2014 at 9:07
Mac OS X uses FreeBSD sed
that allows escaped newlines in its replacement string.
The following version of the solution given by F. Hauri works for GNU sed 4.2.1
, FreeBSD sed
and minised 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'
tac
. :-)