sudhir kumar
sudhir kumar

Reputation: 115

Sed string reverse

I am trying to write sed command to reverse a string. eg: If I enter "america" as input output should be "acirema".

Please help.

FYI: I am able to do this using shell script, Python script. But I couldn't do it using SED.

Upvotes: 1

Views: 8955

Answers (4)

Beta
Beta

Reputation: 99094

Another solution that does not require GNUsed:

sed -e 's/^/\
/' -e ':a' -e 's/\n\(.*\)\(.\)/\2\
\1/
ta' -e 's/\n//'

Upvotes: 0

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed -r 'G;:a;s/^(.)(.*\n)/\2\1/;ta;s/\n//' file

Append a newline using the default hold buffer. Append/insert the first non-newline character following the newline. Repeat until failure, then remove the (leading) newline.

Upvotes: 3

ghoti
ghoti

Reputation: 46826

In addition to the version from the GNU sed manual, you can do this in non-GNU sed if you don't mind doing it in two stages.

$ echo Canada | sed $'s/./&\\\n/g' | sed -ne $'x;H;${x;s/\\n//g;p;}'
adanaC

This uses format substitution to include newlines in the scripts. It works by first separating the input string into one line per character, and then by inserting characters into the beginning of the hold buffer.

What? Inserting characters?

Sure... x swaps the hold space and the pattern space, abd H appends the (current) pattern space to the hold space. So for every character, we place that character into the hold space, then append the old hold space to it, thus reversing the input.

The final command removes the newlines in order to reconstruct the original string.

This should work for any single string, but it will concatenate multi-line input into a single output string.

Upvotes: 4

Thor
Thor

Reputation: 47099

There is an example of this in the GNU sed manual:

rev.sed

/../! b

# Reverse a line.  Begin embedding the line between two newlines
s/^.*$/\
&\
/

# Move first character at the end.  The regexp matches until
# there are zero or one characters between the markers
tx
:x
s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/
tx

# Remove the newline markers
s/\n//g

Run it like this:

echo america | sed -f rev.sed

Output:

acirema

Basically the idea is the mark the start and end of the string with new-lines, then, while the new-lines are moved through the string, swap the adjacent characters.

Upvotes: 7

Related Questions