16

I'm trying to write a bash script that takes a few variables and then does a find/replace with a given file search using grep to get the list of files that have the string. I think the issue I'm having is having the variables be seen in sed I'm not sure what else it might be.

if [ "$searchFiles" != "" -a "$oldString" != "" -a "$newString" != "" ]; then
   echo -en "Searching for '$searchFiles' and replacing '$oldString' with '$newString'.\n"
   for i in `grep $oldString $searchFiles |cut -d: -f1|uniq`; do
      sed -i 's/${oldString}/${newString}/g' $i;
   done
   echo -en "Done.\n"
else
   usage
fi
krizzo
  • 1,823
  • 5
  • 30
  • 52
  • 1
    You need double quotes for variable substitution in bash I think - `sed -i "s/${oldString}/${newString}/g" $i;` – arunkumar Aug 11 '11 at 22:50

2 Answers2

34

use double quotes so the shell can substitute variables.

for i in `grep -l $oldString $searchFiles`; do
  sed -i "s/${oldString}/${newString}/g" $i;
done

if your search or replace string contains special characters you need to escape them: Escape a string for a sed replace pattern

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
8

Use double quotes so the environmental variables are expanded by the shell before it calls sed:

  sed -i "s/${oldString}/${newString}/g" $i;

Be wary: If either oldString or newString contain slashes or other regexp special characters, they will be interpreted as their special meaning, not as literal strings.

Conspicuous Compiler
  • 6,403
  • 1
  • 40
  • 52