3

I have a script I wrote that's supposed to replace the URLs referenced in all files in a directory with a local address, and it doesn't seem to be working, and I'm wondering if somebody can provide me some insight and tell me what I'm doing wrong.

My script is as follows:

#!/bin/bash
#script to replace OLDSTR with NEWSTR in all files in the directory the script is run from
OLDSTR="http://some.external.url/path/to/file"
NEWSTR="file:///local/path/to/file"

( shopt -s globstar dotglob;
    for file in **; do
        if [[ -f $file ]] && [[ -w $file ]]; then
            if [ $file != ".fix" ]; then
                echo "sed -i -- 's#$OLDSTR#$NEWSTR#g' "$file""
                sed -i -- 's#$OLDSTR#$NEWSTR#g' "$file"
            else
                echo "Skipped self"
            fi
        fi
    done
)

Because I'm working with URLs and native unix paths, I opted to use # as the delimiter for sedrather than / as is frequently used in the answers to other sed-related questions.

The loop echoes out each file parsed, correctly matches the script itself and skips it, but no files are actually altered. I've been messing around with this for several days now and really annoyed!

1
  • 1
    Shell variables are not expanded within single quotes, so it's trying to replace literal strings $OLDSTR with $NEWSTR Aug 24, 2016 at 16:31

2 Answers 2

4

As mentioned by steeldriver, the single quotes suppress all shell expansions, so $OLDSTR is passed literally to sed. Since it doesn't actually occur in the files, it doesn't match anything, so nothing is done. You can pass variables to sed using double quotes:

 sed -i -- "s#$OLDSTR#$NEWSTR#g" "$file"

but perhaps in general it is safer to turn the strong quoting on and off, and double quote the variables as you normally would

 sed -i -- 's#'"$OLDSTR"'#'"$NEWSTR"'#g' "$file"
1

Well, I gave up on mucking about with sed after I discovered Regexxer, which was exactly what I needed. sed has it's uses, no doubt, but Regexxer was much simpler and way faster.

It's available in Ubuntu repository and can be installed with this command

sudo apt-get install regexxer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .