简体   繁体   中英

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.

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.

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.

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.

Another solution that does not require GNUsed:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM