3

I have a shell script here that works online, but do not work locally on terminal. What could be the possible reason? How should I debug?

#!/bin/bash

string='internal func add() -> Int'

sed -e '
s/^.*func \+//
s/ *\->.*$//
s/:[^,)]\+/:/g
s/[, ]//g
' <<< "$string"

echo $SHELL

For the input that is present in the shell script, I get internalfuncadd() on local computer, instead of add() - which is the correct output that I get online.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
prabodhprakash
  • 3,825
  • 24
  • 48

1 Answers1

3

Your problem is that you're using BSD sed (as comes with Mac OS X) instead of GNU sed (as is typically found on Linux). BSD sed does not support some features of GNU sed, including \+ in basic regexes. You can instead use \{1,\}:

#!/bin/bash

string='internal func add() -> Int'

sed -e '
s/^.*func \{1,\}//
s/ *\->.*$//
s/:[^,)]\{1,\}/:/g
s/[, ]//g
' <<< "$string"

...or switch to extended regex flavour with -E, although this will require the regexes to be written in that syntax. (In this particular case, the required change is to use + instead of \+; \+ means a literal + in extended syntax)

Wintermute
  • 42,983
  • 5
  • 77
  • 80
  • Oh wow, that works ! - Can you help me with some link to understand these stuffs ? – prabodhprakash Dec 10 '16 at 17:41
  • I don't know a comprehensive list of the differences between GNU sed and BSD sed, unfortunately. – Wintermute Dec 10 '16 at 17:45
  • 3
    What I can give you are links to the parts about sed and regexes in the POSIX standard: http://pubs.opengroup.org/onlinepubs/009695399/utilities/sed.html and http://pubs.opengroup.org/onlinepubs/7908799/xbd/re.html -- those are the things every sed under the sun should support. Both BSD and GNU sed extend POSIX in different ways, though. I hope that helps a little. – Wintermute Dec 10 '16 at 17:48
  • Nicely done. @prabodhprakash: I've tried to summarize all differences in [this answer](http://stackoverflow.com/a/24276470/45375). – mklement0 Dec 10 '16 at 17:58
  • 1
    Thanks @mklement0 - it helps. – prabodhprakash Dec 10 '16 at 18:49
  • 1
    @mklement0 I've probably linked to this answer 30 times by now ;) – Benjamin W. Dec 10 '16 at 19:55