简体   繁体   中英

Search a word in file and replace in Perl

I want to replace word "a" to "red" in a.text files. I want to edit the same file so I tried this code but it does not work. Where am I going wrong?

@files=glob("a.txt");
foreach my $file (@files)
{
    open(IN,$file) or die $!;
    <IN>;
    while(<IN>)
    {
       $_=~s/a/red/g;
       print IN $file;
    }

   close(IN)
}

I'd suggest it's probably easier to use perl in sed mode:

perl -i.bak -p -e 's/a/red/g' *.txt

-i is inplace edit ( -i.bak saves the old as .bak - -i without a specifier doesn't create a backup - this is often not a good idea).

-p creates a loop that iterates all the files specified one line at a time ( $_ ), applying whatever code is specified by -e before printing that line. In this case - s/// applies a sed-style patttern replacement to $_ , so this runs a search and replace over every .txt file.

Perl uses <ARVG> or <> to do some magic - it checks if you specify files on your command line - if you do, it opens them and iterates them. If you don't, it reads from STDIN .

So you can also do:

 somecommand.sh | perl -i.bak -p -e 's/a/red/g' 

In your code you are using same filehandle to write which you have used for open the file to reading. Open the same file for write mode and then write.

Always use lexical filehandle and three arguments to open a file. Here is your modified code:

use warnings;
use strict;

my @files = glob("a.txt");
my @data;
foreach my $file (@files)
{
    open my $fhin, "<", $file or die $!;
    <$fhin>;
    while(<$fhin>)
    {
        $_ =~ s/\ba\b/red/g;
        push @data, $_;
    }
    open my $fhw, ">", $file or die "Couldn't modify file: $!";
    print $fhw @data;
    close $fhw;
}

Here is another way (read whole file in a scalar):

foreach my $file (glob "/path/to/dir/a.txt")
{
    #read whole file in a scalar
    my $data = do {
        local $/ = undef;
        open my $fh, "<", $file or die $!;
        <$fh>;
    };
    $data =~ s/\ba\b/red/g; #replace a with red,

    #modify the file
    open my $fhw, ">", $file or die "Couldn't modify file: $!";
    print $fhw $data;
    close $fhw;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM