Sed "undefined label" on MacOS

I recently found out that this simple sed expression works fine on Linux or under Cygwin, but on Mac it doesn't work with the "undefined" error:

 $ sed '/SUCCESSFUL/d ; /\[java\]/!b label; s/\s\+\[java\]//; /^\s*$$/d; /Compiling/!d; :label /^\s*$$/d; s/^/monitor: /' sed: 1: "/SUCCESSFUL/d ; /\[java ...": undefined label 'label; s/\s\+\[java\]//; /^\s*$$/d; /Compiling/!d; :label /^\s*$$/d; s/^/monitor: /' 

sed on MacOS is a BSD variant with different variants than the GNU counterpart. However, man sed clearly indicates that the MacOS sed version supports labels, so why this error and most importantly, how to solve it?

+7
source share
2 answers

The label name ends with the first literal new line, not a semicolon. There are two easy ways to solve the problem. Add literal lines:

  sed '/SUCCESSFUL/d /\[java\]/!b label s/\s\+\[java\]// /^\s*$$/d; /Compiling/!d :label /^\s*$$/d s/^/monitor: /' 

Or use a few -e options:

 sed -e '/SUCCESSFUL/d ; /\[java\]/!b label' \ -e 's/\s\+\[java\]//; /^\s*$$/d; /Compiling/!d' \ -e':label' -e'/^\s*$$/d; s/^/monitor: /' 
+3
source

There are many similar questions on SO, but most of them are related to -i behavior that is different between platforms, so this is different.

In this case, the problem is quite simple: it seems that label references can only be returned in the BSD sed version, while the GNU version allows direct links. That is, on MacOS,: :label should appear before b label .

The solution is to rewrite the expression either to define the label in front of the branch, or in the case of the expression above to implement the branch - it's kind of "if this template is missing ... jump forward". In this case, the expression can be expanded so as not to require a label in the first place:

 sed '/SUCCESSFUL/d ; /\s+\[java\]\s*/d; /\[java\]/s/\s\+\[java\]//; /Compiling/!d; /^\s*$$/d; s/^/monitor: /' 
+2
source

All Articles