简体   繁体   English

sed字符串反向

[英]Sed string reverse

I am trying to write sed command to reverse a string. 我正在尝试编写sed命令来反转字符串。 eg: If I enter "america" as input output should be "acirema". 例如:如果我输入“ america”作为输入,则输出应为“ acirema”。

Please help. 请帮忙。

FYI: I am able to do this using shell script, Python script. 仅供参考:我可以使用Shell脚本(Python脚本)来执行此操作。 But I couldn't do it using SED. 但是我无法使用SED做到这一点。

There is an example of this in the GNU sed manual : GNU sed手册中有一个示例:

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. 除了GNU sed手册中的版本以外,如果您不介意分两个阶段进行操作,则可以在非GNU sed中进行。

$ 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. 当然... x交换保留空间和模式空间,abd H将(当前)模式空间附加到保留空间。 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): 这可能对您有用(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: 不需要GNUsed的另一个解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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