reverse file character by character using tac
To reverse a file character-by-character using tac
, use:
tac -r -s 'x\|[^x]'
This is documented in info tac
:
# Reverse a file character by character. tac -r -s 'x\|[^x]'
-r
causes the separator to be treated as a regular expression. -s SEP
uses SEP
as the separator. x\|[^x]
is a regular expression that matches every character (those that are x
, and those that are not x
).
$ cat testfile
abc
def
ghi
$ tac -r -s 'x\|[^x]' testfile
ihg
fed
cba%
$
tac file
is not the same as cat file
unless file
has only one line. tac -r file
is the same as tac file
because the default separator is \n
, which is the same when treated as a regular expression and not.
If you're not concerned about the LF character (see mosvy's comments), then it is much more efficient to use rev
rather than tac -r -s 'x\|[^x]'
, piping it to tac
if needed.
$ cat testfile
abc
def
ghi
$ rev testfile
cba
fed
ihg
$ rev testfile|tac
ihg
fed
cba
This solution is way cheaper than tac -r -s 'x\|[^x]'
because regular expressions tend to slow things down quite dramatically.