Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse text file in Bash

Tags:

bash

shell

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
like image 873
user3722544 Avatar asked Jun 10 '14 06:06

user3722544


People also ask

How do I reverse text in bash?

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.

How do you reverse a file in Linux?

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.

How do you reverse the contents of a file in shell script?

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.


1 Answers

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.

like image 84
Avinash Raj Avatar answered Oct 20 '22 05:10

Avinash Raj