четвъртък, 23 декември 2010 г.

Script to find and replace text in multiples files

Ok, I wanted to find a way to edit multiple files (mostly html files) for my site, finding and replacing certain text in them. Here's my progress so far. Please, don't laugh at my efforts, I'm not a bash programmer, I know how to do basic stuff, but this is not my job, not even my hobby. So, if there is simpler and more obvious way - just let me know.
I used following resources: site 1 and site 2 to produce following script: 

#!/bin/bash
     for fl in *.txt; do
     mv $fl $fl.old
     sed "s/$1/$2/g" $fl.old > $fl
     rm -f $fl.old
     done

What it does is to look for a certain string $1 in all the txt files in the directory and to replace it with $2, where you start the script with
sh name.sh $1 $2
where you put the strings $1 and $2 in ' '.
It works beautifully and replaces the strings as it's supposed to. My major
problem with it is that the strings aren't supposed to include "/" in them. Which when you edit an html file is bad. If you want to use that character, you need to "escape" it with "\" meaning that '</div>' will have to become '<\/div>'. I wanted to make a script that will do that automatically, but so far without success. But still, you can easily replace a line with other one or two using this script. And that was the point so. Cheers.
P.S. For more useful info on "sed" look here.

Няма коментари:

Публикуване на коментар