Issue
I am struggling to use sed to replace the mathematical expressions. For even though the regular expression \( \- xi\*\*2 \+ 2\*xi \- 1\)
rel="nofollow noreferrer">matches the string "( - xi**2 + 2*xi - 1)" sed does not perform the substitution:
echo "( - xi**2 + 2*xi - 1)" | sed -e 's/\( \- xi\*\*2 \+ 2\*xi \- 1\)/k1/g'
Please advise.
Solution
You selected the PCRE2 option at regex101.com, while sed
only supports POSIX regex flavor.
Here, you are using a POSIX BRE flavor, so the expression will look like
#!/bin/bash
s="( - xi**2 + 2*xi - 1)"
sed 's/( - xi\*\*2 + 2\*xi - 1)/k1/g' <<< "$s"
See the online demo. In POSIX BRE, this expression means:
(
- a(
char (when not escaped, matches a(
char)- xi
- a fixed string\*\*
- a**
string (*
is a quantifier in POSIX BRE that means zero or more)2 + 2
- a fixed2 + 2
string as+
is a mere+
char in POSIX BRE\*
- a*
charxi - 1)
- a literalxi - 1)
fixed string,)
in POSIX BRE matches a literal)
char.
If you plan to use POSIX ERE, you will need to escape (
, )
and +
in your regex:
sed -E 's/\( - xi\*\*2 \+ 2\*xi - 1\)/k1/g'
Note the difference between -e
(that says that the next thing is the script to the commands to be executed) and -E
(that means the regex flavor is POSIX ERE).
Answered By - Wiktor Stribiżew Answer Checked By - Dawn Plyler (WPSolving Volunteer)