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?
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:
kent$ echo "aaasdf
xaaasdf"|sed 's/\(.\?\)aaa/\1bbb/'
bbbsdf
xbbbsd
kent$ echo "aaasdf
xaaasdf"|sed -r 's/(.?)aaa/\1bbb/'
bbbsdf
xbbbsdf