Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: find & replace a string in perl

by davido (Cardinal)
on Nov 25, 2010 at 13:53 UTC ( [id://873642]=note: print w/replies, xml ) Need Help??


in reply to find & replace a string in perl

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.


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-25 12:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found