dukevin
dukevin

Reputation: 23188

Global substitution shell script not working

I have a shell script like:

for fl in /home/dr/*.txt; do
mv $fl $fl.old
sed 's#$1#$2#g' $fl.old > $fl
rm -f $fl.old
done

and I run it like ./script.sh find replace, yet nothing happens and there is no output. Why is this?

Upvotes: 2

Views: 154

Answers (2)

David Cain
David Cain

Reputation: 17333

The problem is that you're using single quotes instead of double quotes. With single quotes, sed interprets the string literally (i.e. it will search for the string $1, not the first argument).

Below is a functioning version of what you were trying to do. Note that I've replaced temporary file usage with sed's "in-place" editing.

for fl in /home/dr/*.txt
do
  sed -i "s#$1#$2#g" $fl
done

However, you can one-line everything!

sed -i "s#$1#$2#g" /home/dr/*.txt

Upvotes: 2

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed -i "s#$1#$2#g" /home/dr*.txt

The problem you had is single quotes around sed commands does not allow interpolation.

Upvotes: 3

Related Questions