Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Multiline search and replace in file(s)

by haukex (Bishop)
on Aug 09, 2020 at 08:03 UTC ( #11120515=note: print w/replies, xml ) Need Help??


in reply to Multiline search and replace in file(s)

You can use the following pattern to slurp and spew a file:

use warnings; use strict; my @files = <Test*_Copy>; for my $modfile (@files) { # read open my $ifh, '<', $modfile or die "$modfile: $!"; my $data = do { local $/; <$ifh> }; # slurp close $ifh; # modify $data =~ s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/s +mg; # write open my $ofh, '>', $modfile or die "$modfile: $!"; print $ofh $data; close $ofh; }

(Slurping can also be shortened to my $data = do { open my $fh, '<', $modfile or die $!; local $/; <$fh> };, though that's a bit less readable if you're not used to it).

Or you can use a nice module like Path::Class or Path::Tiny:

use warnings; use strict; use Path::Tiny; my @files = path(".")->children(qr/^Test.*_Copy$/); for my $modfile (@files) { $modfile->edit(sub { s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/smg; }); }

Or you can use a oneliner:

perl -wMstrict -0777 -i -pe 's/Marry Had A\nLittle Lamb\nShe Was GOOD\ +n/CHANGED!!!\n/smg' Test*_Copy

Or you can use my module File::Replace for atomic updates when the filesystem supports it:

use warnings; use strict; use File::Replace 'replace3'; my @files = <Test*_Copy>; for my $modfile (@files) { my ($infh,$outfh,$repl) = replace3($modfile); my $data = do { local $/; <$infh> }; $data =~ s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/s +mg; print $outfh $data; $repl->finish; }

Or you can open the file in read-write mode, truncate it after reading, and then write it - though note I see this being done very rarely. (Update: It's useful if you want to flock the file while editing.)

use warnings; use strict; my @files = <Test*_Copy>; for my $modfile (@files) { open my $fh, '+<', $modfile or die "$modfile: $!"; my $data = do { local $/; <$fh> }; $data =~ s/Marry Had A\nLittle Lamb\nShe Was GOOD\n/CHANGED!!!\n/s +mg; seek $fh, 0, 0 or die $!; truncate $fh, 0 or die $!; print $fh $data; close $fh; }

Note that glob has several caveats, though as shown in this code it's ok.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11120515]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2021-02-24 21:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?