Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Replacing text in many files, including binaries

by lancer (Beadle)
on Jun 02, 2011 at 14:19 UTC ( #907799=CUFP: print w/ replies, xml ) Need Help??

I had a bunch of files, some of them binary, that needed to have a text replaced in all of them.

Here's the code that worked for me. It's a one liner, though quite a long line. I also launched it from a Linux shell.

find . -type f | /usr/bin/perl -e 'use feature ":5.12"; use File::Slur +p; for (<STDIN>) { chomp; $a = read_file ( $_, { binmode => ":raw" } +); $a =~ s/<div>Comments<\/div>/<div class="red">Comments<\/div>/g; w +rite_file ($_, { binmode => ":raw" }, $a); }'

Comment on Replacing text in many files, including binaries
Download Code
Re: Replacing text in many files, including binaries
by FunkyMonk (Canon) on Jun 02, 2011 at 15:30 UTC
    You might like to try File::Slurp version 9999.17 or later. Specifically, the edit_file function should shorten your one-liner.
Re: Replacing text in many files, including binaries
by jwkrahn (Monsignor) on Jun 02, 2011 at 22:30 UTC

    If you are running this on Linux then you don't have to worry about the difference between "text" and "binary".

    perl -0777pe's!<div>Comments</div>!<div class="red">Comments</div>!g' +`find . -type f`
Re: Replacing text in many files, including binaries
by xenu (Novice) on Jun 05, 2011 at 15:00 UTC
    One tip from me: You can use
    perl -E 'foobar'
    instead of:
    perl -e 'use feature ":5.12"; foobar'
Re: Replacing text in many files, including binaries
by mrdvt92 (Novice) on Jul 19, 2011 at 04:10 UTC
    I know this is a Perl list but the stream editer does in-place string replacement as one of it's "things".
    find . -type f -exec sed -i 's/<div>Comments<\/div>/<div class="red">C +omments<\/div>/g' {} \;
       s/ sed -i / perl -pi /

      (approximately. the regex will have to be converted to perl as well.)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://907799]
Front-paged by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2014-07-14 08:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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








    Results (257 votes), past polls