http://qs1969.pair.com?node_id=261506

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

    s/123456/234165/g
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.