need help porting a sed command from debian to OSX

2020-07-16 08:58发布

问题:

This is one for you sed gurus out there. I really don't know enough about sed to take this apart completely. It was written on some standard Linux distro and I need it to run on OSX.

COMPILE_FILES=$(sed -nr '/<script type="text\/javascript"/ { s%^.*src="\{\$baseUrl\}/([^"]+)".*$%\1%p }' templates/common/minifiedScripts.tpl)

The first thing is that the r flag doesn't exist on the OSX version of sed. I thought the equivalent is -E, so changed it. But then I get:

sed: 1: "/<script type="text\/ja ...": bad flag in substitute command: '}'

Thanks!

回答1:

OS X sed doesn't like multiple commands run together using semicolons or grouped in curly braces (which aren't necessary in the command you have). Try this:

COMPILE_FILES=$(sed -n -E '/<script type="text\/javascript"/ s%^.*src="\{\$baseUrl\}/([^"]+)".*$%\1%p' templates/common/minifiedScripts.tpl)

If you have a sed script that consists of multiple commands, you'll have to break them up using -e:

sed -n -E -e '/match/ {' -e 's/foo/bar/' -e 's/baz/qux/' -e 'p' -e '}'


回答2:

-r uses the extended regular expression set, and you are using one not supported by the OSX version. Try MacPorts or Fink -- they have ports of gnu sed. OR you can just download and compile source directly.