11

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
2

2 Answers 2

27

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.

2
  • 7
    +1; OSX users: tac is not available there, use tail -r instead.
    – mklement0
    Jun 10, 2014 at 14:01
  • Under OsX, try this for replacing tac: sed -n -e '1!G' -e '$p' -e h or simplier: sed -ne '1!G;$p;h' Nov 4, 2014 at 9:07
0

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.