Home > Enterprise >  sed branching not working on OSX: undefined label
sed branching not working on OSX: undefined label

Time:11-25

I'm trying to adapt the answer from https://stackoverflow.com/a/66365284/1236401 that adds control flow to provide match status code:

cat file.txt | sed 's/1/replaced-it/;tx;q1;:x'

It works as expected on Ubuntu and Alpine, but fails on Mac OSX (11.6), using any shell.

sed: 1: "s/1/replaced-it/;tx;q1;:x": undefined label 'x;q1;:x'

All references I could find to sed misbehaving on OSX were for in-place file edit, which is not the case here.

CodePudding user response:

Commands in sed are separated primarily by newlines.

| sed 's/1/replaced-it/
  tx
  q1
  :x
'

Alternatively:

sed -e 's/1/replaced-it/' -e 'tx' -e 'q1' -e ':x'

Additionally q1 is a GNU sed extension - it's not supported in every sed. It has to be removed, refactored, or you have to install GNU sed.

Overall, write it in awk, python or perl.

CodePudding user response:

Here is an Awk refactoring.

awk '/1/ { sub("1", "replaced-it", $0); replaced=1 } 1
    END { exit 1-replaced }' file.txt

Notice also how the cat is useless (with sed too, and generally any standard Unix command except annoyingly tr).

  • Related