replace words in files??

Started by
2 comments, last by __tunjin__ 19 years, 8 months ago
Hi, i have about 100 files and in each one of them i have to replace a couple of words. How can i do that without having to open each and every file with a editor? Can 'grep' do something for me??
Advertisement
I don't know the answer off-hand (I'm in Windows ATM, so I can't do a full check), but I think sed is what you want. You can give sed a regular expression and using re-directions have it run the replacement and output it to a file. It's a pretty common problem, so googling sed should come up with something.

EDIT - sed is a stream editor application, in case you were wondering.
Yup, sed is what you want. You want to use its regex replacement
features. Like this:

sed -e "s/<find>/<replacewith>/g"

Where <find> is a regex that details what it is you would like
to find and <replacewith> is what you are going to replace it
with. Also, the s stands for the "search and replace"
functionality and the g at the end means to do it globally. This
means that if the search pattern ( <find> ) occurs more than once
in a line then all instances will be relpaced.

Also, the syntax above is assuming that you have redirected the
file to sed, so something like:

cat file | sed -e "s/<find>/<replacewith>/g"

and the results will be printed to stdout.
and the fully automated solution:

for name in *.html; do cat $name | sed -e "s/CAT/DOG/g" > alteredfiles/$name; done

This topic is closed to new replies.

Advertisement