Tugger the SLUGger!SLUG Mailing List Archives

Re: [SLUG] awk sed (grep?)


>>>>> "Robert" == Robert Thorsby <robert@xxxxxxxxxxxxxx> writes:

Robert> On 2006.05.26 18:37 john hedge wrote:
>> I've been hitting my head all day over awk and sed (grep?)!
>> 
>> My challenge is to search a directory of text files for a string
>> which I want to replace wherever it occurs with a new string and
>> save the file with the changes in the same original file name.

Robert> Try a loop using grep with the -q option to locate the files
Robert> with the requisite text then sed with the -i option to make
Robert> the change.  Something like:

Robert> cd /path/to/directory/ for FILE in do if grep -q "text to be
Robert> replaced" "$FILE" then sed -i 's/text to be
Robert> replaced/replacement text/g' "$FILE" fi done

Alternatively, and more brute force, do:
	       for i in *
	       do
		sed 's/string/repl/g' < $i > $i.backup && mv $i.backup $i
	       done

This of course assumes there are no files called x.backup in the
directory.

Or use ed:

   for i in *
   do
   ed - $i <<\EOF
   1,$s/str/repl/g
   w
   q
   EOF
   done

-- 
Dr Peter Chubb  http://www.gelato.unsw.edu.au  peterc AT gelato.unsw.edu.au
http://www.ertos.nicta.com.au           ERTOS within National ICT Australia