1

Is there a way to replace characters from inside the regex?

like so:

find x | xargs perl -pi -e 's/(as dasd asd)/replace(" ","",$1)/'

From OP's comment

code find x | xargs perl -pi -e 's/work_search=1\/ttype=2\/tag=(.*?)">(.*?)<\/a>/work\/\L$1\E\" rel=\"follow\">$2<\/a>/g'

in this case i want $1's spaces be replaced with _

Toto
  • 89,455
  • 62
  • 89
  • 125
Pavel
  • 964
  • 1
  • 6
  • 18

2 Answers2

2

You can use a nested substitution:

$ echo 'foo bar baz' | perl -wpE's/(\w+ \w+ \w+)/ $1 =~ s# ##gr /e'
foobarbaz

Note that the /r modifier requires perl v5.14. For earlier versions, use:

$ echo 'foo bar baz' | perl -wpE's/(\w+ \w+ \w+)/my $x=$1; $x=~s# ##g; $x/e'
foobarbaz

Note also that you need to use a different delimiter for the inner substitution. I used #, as you can see.

ikegami
  • 367,544
  • 15
  • 269
  • 518
TLP
  • 66,756
  • 10
  • 92
  • 149
  • 1
    This answer could be improved by adding spaces around the "=~" – zgpmax Jan 23 '12 at 19:04
  • 2
    @hochgurgler Perhaps readability could be improved, but I detest one-liners that are so long that they trigger the scrollbar. – TLP Jan 23 '12 at 19:07
0

As far as I understand, you want to remove the spaces. Is it correct?

You can do:

s/(as) (dasd) (asd)/$1$2$3/
Toto
  • 89,455
  • 62
  • 89
  • 125
  • correct, but the "(as dads asd)" is just a part of the regex - sorry for confusion, but i didn't post the entire regex: `code` find x | xargs perl -pi -e 's/work_search=1\/ttype=2\/tag=(.*?)">(.*?)<\/a>/work\/\L$1\E\" rel=\"follow\">$2<\/a>/g' in this case i want $1's spaces be replaced with _ – Pavel Jan 23 '12 at 18:54
  • S & A Homes should become S & A Homes – Pavel Jan 23 '12 at 18:58
  • @user845435: Please edit you question instead of add comment with code. – Toto Jan 23 '12 at 19:00