image
image
Ticket Options
Question Details
TICKET ARCHIVE -> Using grep to find and replace all
frozendice - Feb 27, 2006 - 9:08 pm
image
image
I have about 15 static html pages I need to edit, the name of a jpg image. I've tried looking at the grep manpage, but it's just way to involved for my level. Does anyone know a line or two, maybe bash script which, could search multiple files, and replace a certian string with a user specified one?

Or are there any other easy ways to do this?
cfr - Feb 27, 2006 - 11:03 pm
image
image
I suspect you need to use something like sed to do what you want. As far as I know, grep can do the searching fine, but sed can search and replace. It would be easiest to write a tailored script, rather than a generic one. Depending on the string you need to find, and the string you need to replace, you may need to escape characters. It would also be best to set it up so that it sends the output to a new set of files, so that if your script does unexpected things, you can start from the original files again. (You can also practise by not specifying an output file. In that case, sed will send the output to the terminal and not actually change or write any files at all. This is a good way to figure out how sed's syntax works. At least, that was my strategy.)

You would use something like:
sed 's/t/r/g' myfile
to change all occurrences of "t" to "r" on all lines of myfile.
sed 's/t/r/g' myfile > myfile.new
would send the output to myfile.new instead of the terminal.

It is a bit difficult to give more specific advice without either repeating the manual for sed (which you can obviously look up with no risk of my typos introducing problems) or knowing exactly what you are trying to substitute for what. If you need to specify the full file name, including the extension, you will need to escape the "." since sed understands this as "any character whatsoever".
sed 's/t\.jpg/r\.jpg/g' myfile > myfile.new

If you have something more specific, let me know and I will either try to help you or, if I think it exceeds my knowledge of sed, I can put it back in the pool for the experts.

- CFR

IF THIS IS YOUR QUESTION AND YOU WISH TO RESPOND, LOGIN HERE FIRST.


Search Engine Friendly URLs by vBSEO 3.1.0