sachin_chat has asked for the wisdom of the Perl Monks concerning the following question:

hi i am having a file , say test.txt , in it i am having string like $res = system("/prj/sw/tool"); i want to change it to $res = system("/prj/vlsi/toolsmodule"); Thanks sachin

Replies are listed 'Best First'.
Re: change a line or string in file
by reneeb (Chaplain) on Jan 19, 2005 at 09:39 UTC
    use Tie::File...

    #! /usr/bin/perl use strict; use warnings; use Tie::File; my $file = 'test.txt'; tie my @array,'Tie::File',$file or die $!; foreach my $line(@array){ $line =~ s~\$res = system("/prj/sw/tool")~\$res = system("/prj/vlsit +/toolsmodule")~; } untie @array;
Re: change a line or string in file
by prasadbabu (Prior) on Jan 19, 2005 at 09:36 UTC
    sachin cat,

    You try this,

    open (FIN, "test.txt")|| die ("test.txt does not exists"); undef $/; $instr = <FIN>; $instr =~ s|/prj/sw/tool|/prj/vlsi/toolsmodule|si; print "$instr";

    Prasad

      hi prasad is your solution takes in to consideration that there are many other lines , other than what i want to replace. Thanks sachinc
        sachin chat,

        $/ is a input record separator, when you read a content in the file, it will undef the newline characters("\n") in the file if we use undef $/;. (default value of input record separator is "\n")

        $instr will take all the contents in the file (not first line alone).

        is your solution takes in to consideration that there are many other lines

        yes, if there is also only one line, you will get the correct output.

        Prasad

        A reply falls below the community's threshold of quality. You may see it by logging in.
Re: change a line or string in file
by Anonymous Monk on Jan 19, 2005 at 09:43 UTC
    perl -pi 's{\Qsystem("/prj/sw/tool")}{system("/prj/vlsi/toolsmodule")} +' test.txt
Re: change a line or string in file
by hsinclai (Deacon) on Jan 19, 2005 at 14:28 UTC
    This is all you have to do:
    perl -pi -e 's!/prj/sw/tool!/prj/vlsi/toolsmodule!;' test.txt
    if you just need to make that one substitution in test.txt, with no other conditions or considerations. Check the -i switch documented in the perlrun POD to see how to make a safe backup of the original file in the process.