Perl: Loop through a file and substitute
Asked Answered
B

3

6

I simply wanna read in a logfile, do a search and replace, and then write out the changes to that same logfile.

What's the best practice way of doing this in Perl?

Browder answered 1/6, 2009 at 13:4 Comment(0)
C
9

I normally code up a one liner for this:

perl -i -pe 's/some/thing/' log.file

See Here

Champ answered 1/6, 2009 at 13:10 Comment(3)
But why can't I use backreferances? Like perl -pi -e "s/foo(.*)bar/bar$1foo/" tezt2 doesn't work..Browder
Your shell is probably corrupting the string. Try replacing your ""s with ''s so that the * doesn't get expanded.Cephalic
While strict is usually pointless for oneliners, enabling warnings with -w will occasionally catch problems for you; you should do it habitually.Valine
S
8

This is often done with a one-liner:

perl -pi.bak -e "s/find/replace/g" <file>

Note the -i.bak portion -- this creates a backup file with the extension .bak. If you want to play without a net you can do this to overwrite the existing file without a backup:

perl -pi -e "s/find/replace/g" <file>
Siple answered 1/6, 2009 at 13:12 Comment(0)
B
2

or you can use sed (I know... you asked about perl):

sed -i 's/find/replace/g' <file>
Breebreech answered 1/6, 2009 at 13:22 Comment(1)
The way sed handles regular expression rules are...different, than Perl's, to say the least.Beeswing

© 2022 - 2024 — McMap. All rights reserved.