-1

I have a bash shell script written as below:

#!/bin/bash
#arg1: pattern to be found
#arg2: pattern to be replaced
#arg3: filename pattern
echo replace $1 by $2 for all $3 files
for  i in `find . -type f -name "$3"`
do
sed  's/$1/$2/g' $i
done

I use this script (say, called SUBS) as:

./SUBS bbb ddd aa

where the file aa has:

aaaa
bbbb
cccc

But, while I expect to see bbbb replaced as dddb, it shows the same content i.e. bbbb. Any clue what is wrong here? Also, I would like to make the same file getting modified after the replacement. How can I do that? This Qs is little similar to sed substitution with bash variables, but in my Qs, I have used a pattern to find and replace as argument to the shell variable.

Community
  • 1
  • 1
Dr. Debasish Jana
  • 6,653
  • 3
  • 24
  • 55

1 Answers1

3

Variables won't expand when put inside single quotes; you need to use double quotes:

sed "s/$1/$2/g" "$i"

To modify the file in place:

sed -i.bak "s/$1/$2/g" "$i"

After the operation the original file will be backed up with .bak extension; if you don't want to keep backup:

sed -i "s/$1/$2/g" "$i"
heemayl
  • 32,535
  • 3
  • 52
  • 57