CLI tip 27: reverse text line wise with tac
You can use tac
to reverse the input line wise. If you pass multiple input files, each file content will be reversed separately.
$ printf 'apple\nbanana\ncherry\nfig and honey\n' | tac
fig and honey
cherry
banana
apple
You can use the -s
option to specify a different string to be used as the line separator (newline is the default separator). When the custom separator occurs before the content of interest, use the -b
option to print those separators before the content in the output as well.
$ cat blocks.txt
%=%=
apple
banana
%=%=
1
2
3
%=%=
red
green
$ tac -b -s '%=%=' blocks.txt
%=%=
red
green
%=%=
1
2
3
%=%=
apple
banana
See CLI tip 8: extract from start of file until matching line for a practical example where reversing input content helps in constructing a solution.
Video demo:
See also tac section from my Command line text processing with GNU Coreutils ebook for more details and examples.