0

I'd like to run a script on release that replaces all url() declarations in a css file with the full domain path, because images are hosted on a static web server.

Example

Current:  background-image: url(/images/menu.gif);
Desired:  background-image: url(http://example.com/images/menu.gif);
Current:  background-image: url('/images/menu.gif');
Desired:  background-image: url('http://example.com/images/menu.gif');
Current:  background-image: url("/images/menu.gif");
Desired:  background-image: url("http://example.com/images/menu.gif");

I have concocted a bash script using sed to do just that, but it does not handle url with quotes url(''), or urls that already have a full path.

 STATIC_HOST="http://example.com"
 sed -i '' "s|url(\([^)]*\)|url($STATIC_HOST\1|g" main.css
2
  • Do you want to ignore ones that already have the full path? Commented Jan 14, 2011 at 20:04
  • Yes, but most importantly I need to be able to handle the single and double quote cases. Updated test cases above. Commented Jan 14, 2011 at 22:53

2 Answers 2

4

Try with this

sed "s|\(url(['\"]\?\)\(/[^)]*\)|\1$STATIC_HOST\2|g" main.css

Put the -i option only when you are sure the result is what you were looking for.

Sign up to request clarification or add additional context in comments.

3 Comments

Remove the url( in the replacement text and Ill switch from -1 to +1
Update \\(url('\?\\) to \\(url(['\"]\?\\) so your script meets the OP's new requirements. Didn't feel like it was right to answer jack you for such a small change.
This should work fine; I have escaped the double quote because otherwise the shell would have interpretated it.
0
|url\(['\"]?([^'\":)]+)['\"]?\)|url($STATIC_HOST\1)|g

where the colon will prevent "http://..." like urls

1 Comment

You should add the comment that you need GNU sed with the '-r` option for your ERE's to work properly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.