I would like to run this regular expression https://regex101.com/r/9LJAjZ/1 using sed or perl to replace the contents of a file.

If I am correct this will never work with sed because sed is always greedy. But how can I make this regex work with perl.

This is what I've got so far:

perl -pi.bak -e "s#url\(\\[\'|\"]((?!data:|\/).*)\\[\'|\"]\)#url\(\\\'/prefix/\1\\\'\)/#g" file.js

example input file:

url(\'font-awesome.woff\') url(\'bont-awesome.woff\') url(\'/favicon.ico\') url(\'data:whatever\')

example output

url(\'/prefix/font-awesome.woff\') url(\'/prefix/bont-awesome.woff\') url(\'/favicon.ico\') url(\'data:whatever\')
  • Possible duplicate of Conditional replacement using sed?
    – Philippos
    Commented Oct 15, 2019 at 10:15
  • Greedyness is not a problem if you take care to exclude the closing ), for example: sed -E "s#url\(\\\'(\[^/][^):]*\))#url\(\\\'/prefix/\1#g"
    – Philippos
    Commented Oct 15, 2019 at 10:26

1 Answer 1


Modifying your command a bit:

$ perl -pe 's#(url\()(\\['\''"])((?!data:|/).*?\2\))#$1$2/prefix/$3#g' foo
url(\'/prefix/font-awesome.woff\') url(\'/prefix/bont-awesome.woff\') url(\'/favicon.ico\') url(\'data:whatever\')

The regex, which I put in single quotes as the benefit of using \' and \" is outweighed by all the additional escaping needed, is:

   _____  ______  __________________ 
    $1     $2 \2         $3
    url(   \'         ...\')
           \"         ...\")

.*? is lazy, and in the replacement, groups are referred to using $1, $2, etc. (unlike in the pattern, where it's \1, \2, etc.).

  • Thank you. This works. But I would need it to work with double quotes as I am in a docker container. the "prefix" text is a variable which should be replaced. perl -pi.bak -e 's#(url()(\['\''"])((?!data:|/).*?\2))#$1$2/${project}-fe/$3#g' file.js
    – brechtvhb
    Commented Oct 15, 2019 at 11:32
  • Found it. What a horrible piece of code ... :) perl -pi.bak -e "s#(url\()(\\\[\\'\\\"])((?!data:|\\/).*?\\2\))#\$1\$2/${project}-fe/\$3#g" file.js
    – brechtvhb
    Commented Oct 15, 2019 at 11:48

You must log in to answer this question.

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