regexperl

How to change a pattern like XX1/XXSomething/XX1/Something to XXSomething/XX1/Something in perl


I'm having a file in which some lines have some patterns like

M1/XX2/XX1 XX2/XX1/XX2/WCLKB XX2/XX1/XX2/P001  
M1/XX4/XX5 XX4/XX5/XX4/WCLKB XX4/XX5/XX4/P001

Here in some patterns XX2 is repeating. I need to change the above line to

M1/XX2/XX1 XX1/XX2/WCLKB XX1/XX2/P001
M1/XX4/XX5 XX5/XX4/WCLKB XX5/XX4/P001

These XX can vary XX[0..9] The code is in Perl.

I tried using some regex but was confused.

 open(FILE,$FilePath);
 @linesInFile = <FILE>;
 close(FILE);
 foreach $item(@linesInFile){
    if(grep(/^XX?\/XX.\/XX)
  #I dont know how to complete this 
}

Solution

  • If you're looking specifically for XXn/XXm/XXn/ (where n is the same number both times), you can use backreferences:

    s{(XX[0-9]+/)(XX[0-9]+/\1)}{$2}g
    

    Here \1 refers back to and matches the same string as the first capturing group, (XX[0-9]+/).

    Live demo:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    while (my $line = readline DATA) {
        $line =~ s{(XX[0-9]+/)(XX[0-9]+/\1)}{$2}g;
        print $line;
    }
    
    __DATA__
    M1/XX2/XX1 XX2/XX1/XX2/WCLKB XX2/XX1/XX2/P001
    M1/XX4/XX5 XX4/XX5/XX4/WCLKB XX4/XX5/XX4/P001
    

    Output:

    M1/XX2/XX1 XX1/XX2/WCLKB XX1/XX2/P001
    M1/XX4/XX5 XX5/XX4/WCLKB XX5/XX4/P001