[NTLUG:Discuss] Linux script question

David Camm dcamm at advwebsys.com
Mon Jun 16 16:28:27 CDT 2003


well, assuming there aren't 100K files that need to be changed....

find [whatever search parms] -exec perl -pi.x -e s/oldstring/newstring/"   {} \;

the -pi.x will save the original file (say xxx.text) as xxx.text.x - just in 
case you made a mistake in the pattern.  of course, we NEVER make mistakes in 
patterns <VERYBIGGRIN>

after checking the results, you can remove the .x files.

david camm
advanced web systems

Rusty Haddock wrote:
> Bug Hunter wrote:
>     >On Mon, 16 Jun 2003, Chris Cox wrote:
>     >
>     >> Pervaz Allaudin wrote:
>     >> > OK I have another linux command question.
>     >> > 
>     >> > I have multiple files in multiple dirs. under a dir. from which I want 
>     >> > to replace a word and then written back; Either in the same files or 
>     >> > another dir. as root.
>     >> > 
>     >> > I got till
>     >> > 
>     >> > find src -iname *.ext | xargs sed /oldtext/newtext/
>     >> > 
>     >
>     >  for a single file:
>     >
>     >  sed /oldtext/newtext/ filename > filename.newfile
>     >  rm -f filename
>     >  mv filename.newfile filename
>     >
>     >  
>     >in bash
>     >
>     >  for i in /dirname/*
>     >do
>     > sed /oldtext/newtext/ $i > $i.newfile
>     > rm -f $i.newfile
>     > mv $i.newfile $i
>     >done
> 
> Be careful here!!!  I see two problems here:
> 	1) Why are you nuking the .newfile you just created???
> 	   Just delete the 'rm' command.
> 
> 	2) If the 'sed' script fails you're still gonna nuke your
> 	   old files!!!  How would 'sed' fail?  Oh, a full file
> 	   system for one way.  There are others.  "Been there,
> 	   lost that!"  One of the better things to do is to join
> 	   the 'mv' to the 'sed' with a '&&'.  This way, if the
> 	   'sed' fails you don't do the 'mv'.  For example:
> 	   	
>     	sed /oldtext/newtext/ $i > $i.newfile && mv $i.newfile $i
> 
> 	    Remember that the SHELL is the one who will create the
> 	    .newfile, not the 'sed' command.  It is created before
> 	    the 'sed' program is even run -- it has to be otherwise
> 	    'sed's stdout won't be connected to anything.
> 
>     >  This was given to me by a fellow named Richard a while back. :)
> 
> Be caseful what Richard tells you for now on. :-)  Yes, it'll work
> (well, remove the 'rm' like) 99.9% of the time.  Alas, 0.1% of the
> time it will lose what you spent 99.9% of the time creating! :-(
> 
> 	-Rusty-





More information about the Discuss mailing list