Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

find & replace a string in perl

by vr786 (Sexton)
on Nov 25, 2010 at 07:37 UTC ( #873590=perlquestion: print w/ replies, xml ) Need Help??
vr786 has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, i am struggling with editing a file , Iam opening a file and replacing string with a comment(#) at start of that line for example: i have a test.txt file in that there is string called "test" , whenever i found the string test , that line should be commented , here is my code

#!/usr/bin/perl -w my $file_name = "test.txt"; open(INF,'./$file_name') || die "file could not open\n"; my @line; while(@line = <INF>) { if ( $line =~ s/test/^\#/g) { open(INF,'>>$file_name') || die "could not open in writ +e mode"; print INF "Matching is done by $line \n"; close(INF); } else { print "No match found \n"; } close(INF); }

Comment on find & replace a string in perl
Download Code
Re: find & replace a string in perl
by k_manimuthu (Monk) on Nov 25, 2010 at 07:51 UTC

    For your code, you use the same file handler (INF) for read and appened. When you are open a file handle for append mode, the file position is shows the end of the file. You may use another file handle for write mode, then you able to got the expected output.

Re: find & replace a string in perl
by Corion (Pope) on Nov 25, 2010 at 07:57 UTC

    This does not do what you think it does. Try this substitution on its own and think about what you see. Good example data would be

    hello test foo thisisjustatest test1 test2 test3

    Hint: The right hand side of a regular expression is not magic, it is just a string.

      i'd try
Re: find & replace a string in perl
by kcott (Abbot) on Nov 25, 2010 at 08:17 UTC

    You have numerous errors here. Add use strict; and use warnings; to the top of your code. Run it again and see if you can figure out some of the problems.

    Your description in not very clear. Without seeing sample input, I'm not sure if you want to change test to #test or Some line with test in it to #Some line with test in it - take a look at perlre.

    Use the three-argument form of open and let Perl tell you why it can't open the file (i.e. or die $!) - your current output of "file could not open" will be of no help to you at all.

    If you're still stuck after that, post your updated code with a sample of input data and whatever output your code produces.

    -- Ken

      Hi, here is my modified code, i want to place the comment(#) start of that line my input file consist this data eg: testing is requrired see/for/test test/data/istesting my output should be testing is requrired #see/for/test #test/data/istesting But what ever iam trying it is not working, can you help

      #!/usr/bin/perl -w use strict; use warnings; my $line = 0; my $file_name = "test.txt"; open(my $fh, '<', $file_name) || die "file could not open $! \n"; while( $line = <$fh>) { if( $line =~ s/\btest\b/^\#/ig ) { print "$line\n"; } } close($fh);

        You don't tell us what your input is and what output you get, and how it is different from what you want.

        Again, your regular expression still does not do what you may think it does.

        $line =~ s/\btest\b/^\#/ig

        The right hand side of a regular expression is a simple string.

        The code:
        if( $line =~ s/\btest\b/^\#/ig ) { print "$line\n"; }
        is definately wrong as Corion has been saying.
        The bit in brackets after the "if" should be a test with a Boolean answer, whereas you've got a substitute command instead. Also if the substitution ever worked you would not be adding a hash in front of the line but replacing "test" with "^#" so your example line "see/for/test " would become "see/for/^#". You want something like:
        if( $line =~ m/test/ ) { $line = "#" . $line; print "$line\n"; }
        You are making something easy into something hard. First, as you read the input file, output changes to a temporary file. Then save a copy of the original file (rename it to something else) and replace it with the new temporary file. This little "dance" with renaming things is done so that at any time if the program should crash (or maybe system reboots!), it is always possible to get the original data back and re-run the program. As a general rule, do not write modified contents directly back into the original file because there will be a window when no data at all exists! If the data set is something important, that might be a very, very bad thing!

        There is no need for a substitute regex here. Nor is there a need for a "/g" global match. Just add a # at the front if the line contains at least one boundary separated token of "test".

        Update:I modified the code with another thought...when writing filters like this, it is usually a good idea to have the property that running the filter more than once is "harmless". In this case, I prevent multiple # from showing up at the front of the line by just a little addition to the "if" clause.

        #!/usr/bin/perl -w use strict; my $file_name = "test.txt"; open(my $in, '<', $file_name) || die "cannot open $file_name for read + $!"; open(my $out, '>', "$file_name.tmp") || die "cannot open $ +p for write $!"; while( <$in>) { print $out "#" if(/\btest\b/i && !/^#/); #only one # at front of li +ne print $out $_; } close ($in); close ($out); # save copy of original file rename ($file_name,"$file_name.bak") || die "problem with rename $!"; # replace original with the modified version rename ("$file_name.tmp", $file_name) || die "problem with rename $!"; = file test.txt before running program testing is requrired see/for/test test/data/istesting = file test.txt after running program testing is requrired #see/for/test #test/data/istesting
Re: find & replace a string in perl
by cdarke (Prior) on Nov 25, 2010 at 10:03 UTC
    replacing string with a comment(#) at start of that line

    That is not as easy as you think. If you want to replace a line then you must replace every character in it. When you look at a text file in an editor like Notepad or vi(1) then it is showing a visual representation - the file is not really like that. For example:
    abc defg hij
    is really like this:
    The detail varies between operating systems, but UNIX and Windows are similar. So, to replace a line with a comment you would have to:
    1. Open the file for read and write
    2. Read the file until you find the line you need
    3. Move the current file position backwards to the start of the line you just read, using seek.
    4. Overwrite each character with a '#' - no more and no less than the original line length.

    It is not worth the effort! Instead it is easier to:
    1. Open the original file for read
    2. Open a new file for write
    3. In a loop, read each record, then decide if it is to be written to the new file.
    4. Write the record, or not, then read the next record, and so on until end-of-file.
Re: find & replace a string in perl
by davido (Archbishop) on Nov 25, 2010 at 13:53 UTC

    Two simple solutions come to mind. First, the one-liner:

    perl -pi.bak -e "$_ = '# ' . $_ if /\btest\b/" filename.txt

    Or the Tie::File approach for simple line by line file handling.

    use strict; use warnings; use Tie::File; tie my @filelines, 'Tie::File' or die $!; foreach ( @filelines ) { $_ = '# ' . $_ if /\btest\b/; } untie @filelines or die $!;

    I know Tie::File isn't sexy in Perl culture, but it gets the job done without much thought.


Re: find & replace a string in perl
by SimonClinch (Chaplain) on Nov 25, 2010 at 14:33 UTC
    Hmm I am not sure I understand either the question or the answers! The way I read it was you wanted to comment out all lines which have the word test in them, which would look like this (also putting the close outside the loop and creating a new file rather than appending which also seems wrong!:
    #!/usr/bin/perl -w my $file_name = "test.txt"; open(INF,'./$file_name') || die "file could not open\n"; open(INFN,'>./${file_name}.new') || die "$!: ${file_name}.new\n"; my @line; while(@line = <INF>) { if ( $line =~ /test/) { print "found at $.: $line $line = "\# $line"; } print INFN $line; } close(INF); close INFN;
    If you really want to append to the file, read it in, close it and then reopen it for append. Anyway, it is usually wrong to open or close the same file inside a loop.

    One world, one people

Re: find & replace a string in perl
by suhailck (Friar) on Nov 26, 2010 at 05:01 UTC
    Another one (using Regex positive lookahead)

    perl -pi -e 's/(?=.*\btest\b)/#/' fileName

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://873590]
Approved by moritz
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2014-07-14 01:05 GMT
Find Nodes?
    Voting Booth?

    When choosing user names for websites, I prefer to use:

    Results (253 votes), past polls