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
To reverse a String in Bash, iterate over the characters of string from end to start using a For loop or While Loop, and append characters such that the order of characters is reversed. Or we can also use rev command to reverse a string.
The 'rev' command in Linux, which is available by default, is used to reverse lines in a file or entered as standard input by the user. The command basically searches for endline characters ('\n') which denote the end of a line and then reverse the characters of the line in place.
tac command reverses the contents of a file or the standard input. The second sed command now joins all the lines together. Note: The tac command is not present in all the Unix flavors.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With