macosshellcommand-linesed

need help porting a sed command from debian to OSX


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!


Solution

  • OS X sed is based on an older POSIX standard which forbade multiple sed-scripts separated by semicolons (instead of separate -e invocations) and requires newlines for sed-commands 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 groups multiple editing commands, you need to use newlines:

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

    Alternatively, chain them in one line using -e (but I find that less readable):

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

    The macOS version mostly adheres to the old POSIX.1-2001 or SUSv3 standard that you can find here:

    [ 2addr ] { function
    function
    ...
    }

    Execute a list of sed functions only when the pattern space is selected. The list of sed functions shall be surrounded by braces and separated by <newline>s, and conform to the following rules. The braces can be preceded or followed by <blank>s. The functions can be preceded by <blank>s, but shall not be followed by <blank>s. The <right-brace> shall be preceded by a <newline> and can be preceded or followed by <blank>s.

    The last variant described in this post is also not strictly documented there and only incorporated later with the Technical Corrigendum 1, XCU/TC1-2008/0133 [262], which explicitly allowed chaining sed fragments, but it is accepted by macOS sed.

    Technical Corrigendum 2, XCU/TC2-2008/0167 [944] then allows chaining editing commands with semicolons in braces, too. Both TCs were merged into the succeeding POSIX standard.