How can I add text instead of replacing while searching and replacing with Perl?

I am trying to do a search and replace using regex in Perl.

The text I'm looking for is:

<space>Number<space>NumberNumberNumber

and I want to replace it:

<space>Number<space>NumberNumberNumberI

I have the following regex that works when searching for a string:

\s[0-9]\s[0-9[0-9][0-9] 

But what should I do with string replacement? Basically, I just want to add an ā€œIā€ to the end.

I use:

perl -pi -e "s/\s[0-9]\s[0-9][0-9][0-9]/I/;" testFile 

but it replaces everything with me, and does not add to it.

+3
source share
2 answers

That's what backlinks are for. Just concatenate the section of text you want to copy using parentheses. The first set of parentheses is available at $ 1, the second at $ 2, etc.

s/(\s[0-9]\s[0-9]{3})/$1I/

Perl 5.10 named capture,

s/(?<bodytext>\s[0-9]\s[0-9]{3})/$+{bodytext}I/

< > - . %+, - .

s/(?<=\s[0-9]\s[0-9]{3})/I/

, Perl 5.10, \K

s/\s[0-9]\s[0-9]{3}\K/I/

Try

perl -pi -e 's/(\s[0-9]\s[0-9][0-9][0-9])/$1I/' filename

, $1 , Perl - . -, , , , , Perl. B:: Deparse:

perl -MO=Deparse -pi -e "s/(\s[0-9]\s[0-9][0-9][0-9])/$1I/" filename

.

BEGIN { $^I = ""; }
LINE: while (defined($_ = <ARGV>)) {
    s/(\s[0-9]\s[0-9][0-9][0-9])/I/;
}
continue {
    print $_;
}
-e syntax OK

, $1 . :

perl -MO=Deparse -pi -e 's/(\s[0-9]\s[0-9][0-9][0-9])/$1I/' filename
BEGIN { $^I = ""; }
LINE: while (defined($_ = <ARGV>)) {
    s/(\s[0-9]\s[0-9][0-9][0-9])/$1I/;
}
continue {
    print $_;
}
-e syntax OK

:

perl -MO=Deparse -pi -e "s/(\s[0-9]\s[0-9][0-9][0-9])/\$1I/" filename
BEGIN { $^I = ""; }
LINE: while (defined($_ = <ARGV>)) {
    s/(\s[0-9]\s[0-9][0-9][0-9])/$1I/;
}
continue {
    print $_;
}
-e syntax OK
+9

2009 - lookbehind , (?<=pattern) \K, - :

%echo "test" | perl -p -e "s/(?<=test)/ing/"
testing
%echo "test" | perl -p -e "s/test\K/ing/"
testing
%

, - , , (?=pattern):

%echo "test" | perl -p -e "s/(?=test)/#/"
#test
%

:

0

Source: https://habr.com/ru/post/1709497/


All Articles