in reply to Modifying A Bunch of Files by replacing specific lines
This assumes that your sections start and end on seperate lines...if that's not the case an slightly different version is required. See perlman:perlrun for the details of the switches.
On a *nix system you don't need the first line of the BEGIN{} block
#! perl -snli.org use strict; use vars qw[$B $E $R $s]; BEGIN{ @ARGV= map{glob}@ARGV; # Not necc. on *nix $s=0 } /<!- $B -->/ .. (/<!- $E -->/ && ($s = 1)) ? ($s and print($R), $s = 0 ) : print
sample usage
C:\test>del junk.in && ren junk.in.org junk.in C:\test>type junk.in -i[*extension*] If the extension doesn't contain a "*", then it is appended to th +e end of the current filename as a suffix. If the extension does contain one or more "*" characters, then each "*" is replaced wit +h the current filename. In Perl terms, you could think of this as: ($backup = $extension) =~ s/\*/$file_name/g; This allows you to add a prefix to the backup file, instead of (o +r in addition to) a suffix: <!- BRS --> $ perl -pi 'orig_*' -e 's/bar/baz/' fileA # backup to 'orig +_fileA' <!- ERS --> Or even to place backup copies of the original files into another directory (provided the directory already exists): $ perl -pi 'old/*.orig' -e 's/bar/baz/' fileA # backup to 'ol +d/fileA.orig' <!- BRS --> These sets of one-liners are equivalent: <!- ERS --> $ perl -pi -e 's/bar/baz/' fileA # overwrite curre +nt file $ perl -pi '*' -e 's/bar/baz/' fileA # overwrite curre +nt file $ perl -pi '.orig' -e 's/bar/baz/' fileA # backup to 'file +A.orig' $ perl -pi '*.orig' -e 's/bar/baz/' fileA # backup to 'file +A.orig' C:\test>test -B=BRS -E=ERS -R="Replacement text" junk.in C:\test>type junk.in -i[*extension*] If the extension doesn't contain a "*", then it is appended to th +e end of the current filename as a suffix. If the extension does contain one or more "*" characters, then each "*" is replaced wit +h the current filename. In Perl terms, you could think of this as: ($backup = $extension) =~ s/\*/$file_name/g; This allows you to add a prefix to the backup file, instead of (o +r in addition to) a suffix: Replacement text Or even to place backup copies of the original files into another directory (provided the directory already exists): $ perl -pi 'old/*.orig' -e 's/bar/baz/' fileA # backup to 'ol +d/fileA.orig' Replacement text $ perl -pi -e 's/bar/baz/' fileA # overwrite curre +nt file $ perl -pi '*' -e 's/bar/baz/' fileA # overwrite curre +nt file $ perl -pi '.orig' -e 's/bar/baz/' fileA # backup to 'file +A.orig' $ perl -pi '*.orig' -e 's/bar/baz/' fileA # backup to 'file +A.orig'
Examine what is said, not who speaks.
The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.
|
|---|