Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Changing file contents

by bh_perl (Monk)
on May 29, 2003 at 07:39 UTC ( #261506=perlquestion: print w/replies, xml ) Need Help??

bh_perl has asked for the wisdom of the Perl Monks concerning the following question:

I have one problem in updating file contents. The problem is how to change the entire words in text file ? As exmpale the filename is test.txt and the contents are "This is my number 123456" and change to "This is my number 234165";

Replies are listed 'Best First'.
Re: Changing file contents
by rnahi (Curate) on May 29, 2003 at 08:06 UTC

    This one liner

    perl -i.bak -pe 's/123456/234165/' filename

    will change only one occurrence of the pattern, modify your file in place and save the old one with a ".bak" extension.

    To change every occurrence of the pattern, use

Re: Changing file contents
by zby (Vicar) on May 29, 2003 at 08:53 UTC
    You have rnahi's answer - it's a shortcut, no offence but I think it's a bit too magic for your level of perl mastery. Here are my instructions:
    • Learn how to open a file handle -  perldoc -f open
    • Learn how to read the file content -  perldoc perlop look for the <> operator.
    • Learn Perl regular expressions -  perldoc perlre
    • Learn the substitution operator  perldoc perlop look for  s/PATTERN/REPLACEMENT/egimosx
    • Learn how to write to a file -  perldoc -f print
    Then the progarm should be obvious.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://261506]
Approved by zby
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2023-02-04 19:06 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (31 votes). Check out past polls.