Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Compact multi-line inplace file edit search and replace

by GrandFather (Saint)
on Aug 22, 2005 at 22:26 UTC ( [id://485784]=CUFP: print w/replies, xml ) Need Help??

This performs a search and replace on a file as an inplace edit. The search string may be multiple lines long, but must be an exact match - including line end characters. This is not any sort of regex match!
my $matchBlock = do {local $/ = ""; <DATA>}; $/ = $matchBlock; @ARGV = ("file_to_inplace_edit.txt"); $^I = '.bak'; while (<>) { my $matched = chomp; print $_; #print everything up to the block to be replaced print "This replaces the matchBlock text\n" if $matched; } __DATA__ match string goes here. As long as you like and spanning lines if you like, but it must match exactly the text to be replaced including the line end characters in the file to be edited must be standard for the OS.
Update: Use chomp per tye's suggestion

Replies are listed 'Best First'.
Re: Compact multi-line inplace file edit search and replace (:
by tye (Sage) on Aug 23, 2005 at 05:21 UTC
Re: Compact multi-line inplace file edit search and replace
by chanio (Priest) on Aug 23, 2005 at 06:18 UTC
    Very creative!

    But I guess that you also need to list the last part of the file.

    That is, like in a huge

    split
    , ain't me right? It looks good for raw XML replacements :) .

    (updated)

    Sorry, I still can't get what the my $matched= chomp; really does... I need more practice, I guess [-(.

    { \ ( ' v ' ) / }
    ( \ _ / ) _ _ _ _ ` ( ) ' _ _ _ _
    ( = ( ^ Y ^ ) = ( _ _ ^ ^ ^ ^
    _ _ _ _ \ _ ( m _ _ _ m ) _ _ _ _ _ _ _ _ _ ) c h i a n o , a l b e r t o
    Wherever I lay my KNOPPIX disk, a new FREE LINUX nation could be established

      Actually you do get the last part of the source file. If there is just one instance of the match text in the original file then the first itteration of the loop prints the part before the match and the replacement text. The second itteration prints the part of the original file following the match text, but does not insert the replacement text.


      Perl is Huffman encoded by design.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-24 23:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found