Concatenate and Write Files in Reverse with tac Command

tac is reverse of cat command in functionality. tac copies each file (- means standard input), or standard input if none are given, to standard output, reversing the records (lines by default) in each separately. Synopsis:

tac [option]… [file]…

A sample run is shown below:

$ tac
gskjhsg
shgsgeg
skheghseg
skheghseg
shgsgeg
gskjhsg

Note that you need to press Ctrl+D before tac will reverse the standard input. Consider a file test.txt with two lines:

line 1
line 2

If we say tac test.txt then following will be the output:

line 2
line 1

-b or --before causes the separator to be attached to the beginning of the record that it precedes in the file.

-r or --regex treats the separator string as a regular expression.

-s separator or --separator=separator uses separator as the record separator, instead of newline. Note an empty separator is treated as a zero byte. I.e., input and output items are delimited with ASCII NUL.

To reverse a file character by charcter you can use: tac -r -s 'x\|[^x]'

Leave a comment

Your email address will not be published. Required fields are marked *