0

I have SED patterns:

[^a-zA-Z0-9]

/b\./s/.*c\.. \([^ ]*\) .*/\1/p

and so on.

I need to pass these to an echo command as variables.

At the moment, I define the $pattern variable like so:

$pattern="[^a-zA-Z0-9]"

and then pipe it to echo, like so:

echo "$OUTPUT" | sed "s/$pattern/g"

But the code is not passing the pattern, but a command and returns the error

=[^a-zA-Z0-9]: command not found

What's going wrong?

ilkkachu
  • 133,243
  • 15
  • 236
  • 397
Michael Riordan
  • 123
  • 4
  • 11
  • Does `pattern='[^a-zA-Z0-9]'` work better? You're not assigning a variable with `$pattern=`. Take a look at `eval` as an alternative too... I can make it into a proper answer if it works... – Zip Dec 07 '17 at 16:55
  • see also: https://unix.stackexchange.com/q/32907/117549 – Jeff Schaller Dec 07 '17 at 17:00
  • `[^a-zA-Z0-9]` is a pattern but `/b./s/.c.. ([^ ]) .*/\1/p` is a full `sed` script. – Stéphane Chazelas Dec 07 '17 at 17:18
  • 1
    Just a little insight on the error. With dollar sign `bash` expands it as if it were a variable and because there was nothing in `$pattern` at that point, `bash` saw this: `=[^a-zA-Z0-9]`. And what's the next step? Executing the command with that name, thus the error. – PesaThe Dec 07 '17 at 17:57

2 Answers2

2
$ pattern='[^a-zA-Z0-9]'
$ echo "123 ABC" | sed "s/$pattern/g"
sed: -e expression #1, char 16: unterminated `s' command
$ echo "123 ABC" | sed "s/$pattern//g"
123ABC
$ echo "123 ABC" | sed "s/$pattern/XYZ/g"
123XYZABC

And...

Shell variables are assigned without a leading $.

FaxMax
  • 716
  • 1
  • 7
  • 27
1

Replace

$pattern="[^a-zA-Z0-9]"

by

pattern="[^a-zA-Z0-9]"

Shell variables are assigned without a leading $.

Patrick Mevzek
  • 3,130
  • 2
  • 20
  • 30