• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 460
  • Last Modified:

conditional replace using Perl

I have a body of text and I want to do a conditional replace based, I am assuming with an if statement.

text example:  So I want to replace part of line 3, the attribute name, which is  "Significance", with a concatenation of line 1 value, in this case, "AtPID LR score" + "Significance".  How do I do this?

line1 <attr name= "mref" value = "AtPID LR score" index = "0" />
line 2<attr name= "Method" value = "AtPID LR score"  index = "0" />
line 3 <attr name= "Significance" value = "1248.12"  index = "0"/>
0
MichelleLacy
Asked:
MichelleLacy
  • 2
  • 2
2 Solutions
 
Adam314Commented:

while(<>) {
    if($. == 1) {my $value = /value\s*=\s*"(.*?)"/;}
    elsif($. == 3) {s/name\s*=\s*"(.*?)"/name="$value$1"/;}
}

Open in new window

0
 
MichelleLacyAuthor Commented:
I am very new to perl, so would you walk me through this a little.
0
 
Adam314Commented:
What I gave was the code to do what you asked - it is not a complete perl program.  Below is a complete program.  Save it to a file.  If you are on windows, it will have to have a ".pl" extension.  On unix, it can be named whatever you want.

To use it, pass the name of the input file on the command line.  Redirect the output to the new file.

For example, if you saved the below code to "dorename.pl", your original file was input.txt, and you wanted to have your new file named "output.txt", you would use this command:
    dorename.pl input.txt > output.txt

#!/usr/bin/perl
use strict;
use warnings;
 
my $value;
while(<>) {
    if($. == 1) {$value = /value\s*=\s*"(.*?)"/;}
    elsif($. == 3) {s/name\s*=\s*"(.*?)"/name="$value$1"/;}
    print;
}

Open in new window

0
 
MichelleLacyAuthor Commented:
thank you.  I used it right away, but forgot to close the session.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now