How to reverse a string using sed

I had got issue with having to reverse a string of number manually. Of course, that gave me a big headache. Thanks to Peter from Catonmat, I’ve got the following sed script.

'/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'

As you can imagine, this is quite complicated, but luckily he’s given nice explanation as well.


sed ‘

/n/ !G

s/(.)(.*n)/&21/

//D

s/.// ‘

The first line “/n/ !G” appends a newline to the end of the pattern space if there was none.

The second line “s/(.)(.*n)/&21/” is a simple s/// expression which groups the first character as 1 and all the others as 2. Then it replaces the whole matched string with “&21″, where “&” is the whole matched text (“12″). For example, if the input string is “1234″ then after the s/// expression, it becomes “1234n234n1″.

The third line is “//D”. This statement is the key in this one-liner. An empty pattern // matches the last existing regex, so it’s exactly the same as: /(.)(.*n)/D. The “D” command deletes from the start of the input till the first newline and then resumes editing with first command in script. It creates a loop. As long as /(.)(.*n)/ is satisfied, sed will resume all previous operations. After several loops, the text in the pattern space becomes “n4321″. Then /(.)(.*n)/ fails and sed goes to the next command.

The fourth line “s/.//” removes the first character in the pattern space which is the newline char. The contents in pattern space becomes “4321″ — reverse of “1234″.

But what I want is the output to be separated by “.” aka dot character. So here’s what I come up with.

$ echo 123456789 | sed '/\n/!G;s/\(.\)\(.*\n\)/&\2.\1/;//D;s/.//'

.9.8.7.6.5.4.3.2.1

Still there’s one small issue, I don’t want dot at the start of the string. So after reading his explanation, I realize that I need to put one more “.” to be replaced at the fourth line. This is final script.

$ echo 123456789 | sed '/\n/!G;s/\(.\)\(.*\n\)/&\2.\1/;//D;s/..//' 

9.8.7.6.5.4.3.2.1

So obviously, if you want “,” aka comma instead of dot, you can just substitute it. If you are curious about getting to know sed, why don’t you head over to catonmat.net. That site got so many cool sed one liners.

Source : Catonmat