Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl, append a character to i-th capturing group

Tags:

regex

perl

I have this one liner:

perl -pe 's|.*?((\d{1,3}\.){3})xxx.*|\1|'

I feed this command with some input, like 192.168.1.xxx, and it works. Now, I want to append a 0 to the output sequence, but of course if I just append the 0 right after the \1 it will be parsed as the tenth capturing group. How can I concatenate then it to the \1 directive?

like image 277
Lorenzo Pistone Avatar asked Feb 09 '12 22:02

Lorenzo Pistone


People also ask

What is S * in Perl?

Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user.

What does =~ mean in Perl?

=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {

What is * in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.

How do I match a character in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.


1 Answers

You should use $1 instead of \1 in substitutions. Then you can use braces to write it unambiguously like this:

perl -pe 's|.*?((\d{1,3}\.){3})xxx.*|${1}0|'
like image 115
Ilmari Karonen Avatar answered Oct 20 '22 12:10

Ilmari Karonen