[NTLUG:Discuss] Linux script question

Rusty Haddock rusty at fe2o3.lonestar.org
Mon Jun 16 15:37:29 CDT 2003


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-
-- 
   _____        Rusty Haddock  =  KD4WLZ  =  rusty at fe2o3.lonestar.org
|\/   o \   o  **Out yonder in the Van Alstyne (TX) Metropolitan Area**
|   (  -<  O o              Microsoft is to software what
|/\__V__/                  McDonalds is to gourmet cooking



More information about the Discuss mailing list