Sed用多次重复的另一个字符替换一个字符的多次重复

时间:2013-08-22 03:34:28

标签: regex sed substitution

如果我有一段文字,但主角的数字重复可以改变。

  

aaaabbbbaaaacccc

我想用a给出

替换文本开头的所有x
  

xxxxbbbbaaaacccc

我希望使用正则表达式sed trawk

6 个答案:

答案 0 :(得分:5)

您可以使用循环:

echo aaaabbbbaaaacccc | sed ':l s/^\(x*\)a/\1x/;tl'

答案 1 :(得分:4)

一个答案在于使用sed的条件分支机制,我认为:

sed ':b; s/^\(x*\)a/\1x/; t b'

它在行的开头用原始的x和另一个a替换了更多x个加上x的零序列。 。 :b创建了一个标签b;如果自上次t b检查后执行了替换,则b会跳转到标记sed

唯一一次遇到麻烦的是你有aaaaxaab之类的行;它会跳过第一个x并在不应该的情况下翻译后续的a

在Mac OS X上进行测试时,我必须将其修改为:

sed -e ':b' -e 's/^\(x*\)a/\1x/' -e 't b' <<< aaaaaxaaab

使用单个脚本参数,该行根本没有更改。 Mac OS X sed偶尔会对GNU sed不是必须使用换行符或新参数的地方很有趣。 (它是:b必须在它自己的参数中或在脚本中的自己的行上;替换和跳转在一个参数中是正常的,中间有一个分号。

答案 2 :(得分:3)

这里至少有一行输入......

我必须做一些奇怪的事情才能得到评论...

echo '{
        h                 ;# copy the line
        s/^(a+)(.*)/\1/   ;# get just the leading aa  aaaa
        y/a/x/            ;# change aa to xx
        x                 ;# swap the xx and the line
        s/^(a+)(.*)/\2/   ;# remove the leading aa from the line  bbbbaaaacccc
        x                 ;# swap bbbbaaaacccc for xxxx
        G                 ;# append bbbbaaaacccc
        s/\n//            ;# get rid of the intervening new line
}' > s2.sed ; echo aaaabbbbaaaacccc | sed -rf s2.sed     

xxxxbbbbaaaacccc


echo '{
        h                 ;# copy the line
        s/^(a+)(.*)/\1/   ;# get just the leading aa  aaaa
        s/a/hello/g       ;# or change stuff to hello...
        x                 ;# swap the xx and the line
        s/^(a+)(.*)/\2/   ;# remove the leading aa from the line  bbbbaaaacccc
        x                 ;# swap bbbbaaaacccc for xxxx
        G                 ;# append bbbbaaaacccc
        s/\n//            ;# get rid of the intervening new line
}' > s3.sed ; echo aaaabbbb| sed -rf s3.sed     

hellohellohellohellobbbb

答案 3 :(得分:2)

Perl:

$ perl -pe 's/^a+/ "hello" x length($&) /e'  <<< aaaabbbbaaaacccc
hellohellohellohellobbbbaaaacccc

答案 4 :(得分:2)

这可能适合你(GNU sed):

 sed 's/a*/&\n/;h;y/a/x/;G;s/\n.*\n//' file

在第一个非a之前放置一个标记。将该行复制到保留空间。更改图案空间中的线条。附加原始行。删除不需要的部分。

a更改为hello

sed 's/a*/&\n/;h;s/a/hello/g;G;s/\n.*\n//' file

答案 5 :(得分:1)

您只需执行以下操作:

echo 'aaaabbbbaaaacccc' | sed 's/^aaaa/xxxx/'