easy way to change string in multiple files?

Steven Elling ellings at kcnet.com
Sun Oct 6 22:17:11 CDT 2002


On Sunday 06 October 2002 19:41, you wrote:
> On Saturday 05 October 2002 21:17, Chris Hoelscher wrote:
> > > Looking for an easy way to change 'string.a' to 'string.b'
> > > in a set of files within one directory.
> >
> > From: Steven Elling [mailto:ellings at kcnet.com]
> > You can do the following if you have perl on your system.
> >
> > perl -pi -e 's/string.a/string.b/g' file-name
> >
> > or
> >
> > perl -pi -e 's/string.a/string.b/g' shell-wildcard
>
>  If you want to make a backup copy of the files -- with a
>
> > '.bak' extension
> > added on -- do the following:
> >
> > perl -pi.bak -e 's/string.a/string.b/g' file-name
> >
> > or
> >
> > perl -pi.bak -e 's/string.a/string.b/g' shell-wildcard
>
> Does this have to run from within the directory?  I have a shell script
> that uses sed, but because of the way it creates temporary files I can't
> give it a path name and it can't walk a tree.
>
> I have a rather complex web site that the owner is using Adobe Pagemill
> (Obsolete & Unsupported) to maintain, and it always refers to files in
> other directories by using "../../" to step back, so we have special
> characters to escape too.

No it does not have to run from within the directory. This method will work
from anywhere no matter what directory you are currently in and it will even
put backup copies in the same directory as the original file.  This command
itself cannot walk the tree, but, you can use find to get a list of files and
then proceed to run perl on that list of files. Something like

for i in `find /path/to/root/of/tree -type f -name '*.htm*' -print`; do
  perl -pi.bak -e 's/string.a/string.b/g' $i
done

One way to reduce the leaning tookpick syndrome is to do the following for
 the substitution:

perl -pi.bak -e 's#../../../../doc.html#/path/to/web/doc.html#g'
file-name

You replace the slashes that delimit the pattern from the replacement with
hashes. Otherwise you have to do the following:

perl -pi.bak -e
's/../../../../doc.html//path/to/web/doc.html/g' file-name

It gets a little messy to say the least.

I'm not exactly sure if you can turn off all special characters, but I don't
think you can.

I should of mentioned this earlier but you can look at 'man perlop' to get
help on using perl operators like that used for the substitution and 'man
perlre' for help on perl regular expressions.

If your really apt at perl you can wright the whole script in perl and not
 use a shell script to find all the files.  Hint:  'man File::Find'.




More information about the Kclug mailing list