Hello,

I’m trying to increment numbers in a file – for instance, I would like to change the below 3 lines in a file by incrementing the numbers by 2 (or whatever the user gives).

Mikef<20:40>
JoeyS<23>
Samt<14:39>

So the end results should look like this:

Mikef<22:42>
JoeyS<25>
Samt<16:41>

I can do it in a command line using this:

>  perl -pe 's/(\d+)/ 2 + $1 /ge' <filename>

But cannot do it inside of a program?

   while ($line = <FILE>) {
        $line =~ s/(\d+)/2 + $line/ge;
        print NEWFILE $line;
   }

The above scripting only replaces all numbers with "2"?
Can you tell me what I am doing wrong?

Thanks,
Mike

Edited 3 Years Ago by pyTony: fixed formatting

Hi!

while ($line = <FILE>) {
    $line =~ s/(\d+)/$1+2/ge;
    print $line;
}

Regards, mawe

Thanks you very much - I guess I had my variables mixed up.
I really appreciate your quick response!
Great site!

Cheers!
mforeman

Hello,

I am now having problems combining a "foreach" or "while" command with a search command. Basically, I need to 1st search a file line by line for a string, then if that string is found to change only the strings that match the search criteria. For instance given the file below I want to search for all the lines that have "Mike" in them. Then if found to increment the numbers by 3. If not found, print out an error message. Can anyone help?

Mikef<20:40>
JoeyS<23>
Samt<14:39>
Mikej<21:41>

Out put should look like this:

Mikef<23:43>
JoeyS<23>
Samt<14:39>
Mikej<24:44>

Thanks,
mforeman

Hi!

Well, you just need one more line ;)

while ($line = <FILE>) {
    if ($line =~ /Mike/) {
        $line =~ s/(\d+)/$1+3/ge;
    }
    print $line;
}

Regards, mawe

Thanks again!

I spent way too much time unsuccessfuly trying to do what you just did. This is very simple and easy to understand (Now that I see it). :cool:

Again - I appreciate your help.
cheers,
mforeman

This question has already been answered. Start a new discussion instead.