Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to change a string in multiple files

Status
Not open for further replies.

zubnus

Programmer
Apr 22, 2003
8
US
Hi All,

I want to change a string say "old_fieldname" to "new_fieldname" in all the files where old_fieldname is present.

do I have to use find command ?? if yes, can anybody please tell me the command.

Thanks in Advance.

 
One way, untested...

For all files in the current directory:
#!bin/sh
for i in *
do
sed 's/old_fieldname/new_fieldname/g'$i > $i
done


 
Do you know the names of all the files that have the old field name in them? If you don't, you can use: find . -print | xargs grep "old field name" to get a list of the files that have the old field name. You could write the list to a file.

Then you can use an awk command to make the changes. Maybe:
for line in 'cat list.txt' [from your find command]
do
awk '{ print $1 'new field name' $3 $4 }'
done

You may have to play around with the part betweeh the { } for correct spacing, etc.


 
[tt]FILES=`find . -type f`
echo $FILES | while read FILE
do
sed 's/old string/new string/g' $FILE > $FILE.$$
mv $FILE.$$ $FILE
done[/tt]
should work too.

//Daniel
 
Yet another solution, but in one convenient line:

[tt]perl -pi.bak -e"s/old_fieldname/new_fieldname/g" filenames[/tt]

Any files modified will be backed up as filename.bak, unless you leave out the .bak part.



Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top