sed相当于PCRE的`。?`

sed相当于PCRE的`。?`

问题描述:

I'm trying to find all instances of aaa and replace it with bbb but preserving the first character preceding the aaa. Here's how I'd do it in PHP with PCRE:

preg_replace('#(.?)aaa#', '\1bbb', 'aaasdfg');

How would I do something like that with sed? Here's my attempt (didn't work):

sed -i.bak -r 's/(.\?)aaa/\1bbb/g' filename.ext

It's a bit of a contrived example. What I'm trying to do is a little more complicated but, long story short, I'm trying to get .? working.

Any ideas?

我正在尝试查找 aaa code>的所有实例并将其替换为 bbb code>但保留 aaa code>之前的第一个字符。 以下是我在PHP中使用PCRE的方法: p>

  preg_replace('#(。?)aaa#','\ 1bbb','aaasdfg'); 
   code>  pre> 
 
 

我如何使用sed做类似的事情? 这是我的尝试(没有用): p>

  sed -i.bak -r's /(。\?)aaa / \ 1bbb / g'filename.ext \  n  code>  pre> 
 
 

这是一个人为的例子。 我想要做的事情有点复杂但是,长话短说,我正在尝试。? code>工作。 p>

任何想法? div>

Just now I mis-read your question, I thought you want to do .*? with sed. ..

Ok, now I understand what you mean. In another question from you, I mentioned, for BRE, you have to escape those chars to give them special meaning. But for ERE, you have to escape chars which have special meaning to get literal string.

You used -r, to let sed use ERE, but you escaped ?, it means, you want to match literal string ?.

try this:

sed -i.bak -r 's/(.?)aaa/\1bbb/g' filename.ext

or this:

sed -i.bak 's/\(.\?\)aaa/\1bbb/g' filename.ext

test:

default with BRE

kent$  echo "aaasdf
xaaasdf"|sed 's/\(.\?\)aaa/\1bbb/'
bbbsdf
xbbbsd

with -r, ERE:

kent$  echo "aaasdf
xaaasdf"|sed -r 's/(.?)aaa/\1bbb/' 
bbbsdf
xbbbsdf