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:

#script to replace OLDSTR with NEWSTR in all files in the directory the script is run from

( 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"
                echo "Skipped self"

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
    Shell variables are not expanded within single quotes, so it's trying to replace literal strings $OLDSTR with $NEWSTR – steeldriver Aug 24 '16 at 16:31

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"
| improve this answer | |

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.