Find and replace in all files using shell scripting

Hi all,

I'm looking to find and replace a string in all HTML files within a certain directory, including subdirectories. Normally, I would play with this a little to get it to work, but I can't mess this up, so I'm going to ask here.

Basically, I want to find "<title>" in all *.htm* files (to include .htm and .html) and replace it with "<title>My Website Name - ". I'm doing a bit of search engine optimization. How should I write a shell script to do this?

Best,
Danny

do you have "-i" option in your sed man page??
if not first do

grep -l "<title>" *.htm*>file_list.txt
while read file_name ; do
sed 's/\<title\>/&My Website Name - /g' $filename > temp_file
mv temp_file $file_name
done < file_list.txt

if you have -i option use only sed command

I do have -i. What do you mean by "use only sed command?"

sed -i 's/pattern/replacestring/g' filename

I'm sorry, I still don't understand how you use that to replace "<title>" in all *.htm* files within a directory and its subdirectories.

First cd to the directory where your html files reside, then to change only the first occurrence of <title> in every record run:

find . -name '*.htm*' -print0 | xargs -0 sed -i 's/<title>/&My Website Name -/'

For every occurrence of <title>...

... sed -i 's/<title>/&My Website Name -/g'

This will change the files in-place, so try the code first with some sample files.

Okay, this works great on my local machine (running linux). But after logging into the web server, I find the sed on that machine doesn't have the -i switch. What should I do?

then use the code that i have given:)

Vidyadhar85, your code didn't seem to work for me. For one, it didn't look in any deeper directories (fixed with grep -lr) and also, the temp file is always blank, so it basically erases the contents of the file. How do I fix it?

sorry i made a small mistake

 
grep -l "<title>" *.htm*>file_list.txt
while read file_name ; do
sed 's/\<title\>/&My Website Name - /g' $file_name > temp_file
mv temp_file $file_name
done < file_list.txt

now it should work:)

Actually, I just noticed that myself, but I still seem to be having problems. For some reason when I try to search recursively through the directory, it won't work for *.htm*, but it will for just *. See the output I listed below. What gives?

vine8:/afs/ir.stanford.edu/group/hopes/WWW/test> grep -l -r "<title>" *.htm*
test.html
vine8:/afs/ir.stanford.edu/group/hopes/WWW/test> grep -l -r "<title>" *
findnreplace.sh
test/form.php
test/mailer.php
test/test.html
test.html

thats because as you see in grep man page whenever you use -r or -R option it expect a dir if you give * it will go through the child dir also but when you specify a file or group of file it will search in . i.e home dir only