Home > Mobile >  Using sed to substitute mathematical expressions
Using sed to substitute mathematical expressions

Time:02-17

I am struggling to use sed to replace the mathematical expressions. For even though the regular expression \( \- xi\*\*2 \ 2\*xi \- 1\) 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.

CodePudding user response:

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 fixed 2 2 string as is a mere char in POSIX BRE
  • \* - a * char
  • xi - 1) - a literal xi - 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).

CodePudding user response:

With your shown samples, please try following in sed. Since you are doing a pattern matching, then IMHO rather than doing substitution we can match pattern and then simply print the new value(by keeping printing off for all lines until we ask sed to print).

s="( - xi**2   2*xi - 1)"
sed -n 's/( - xi\*\*2   2\*xi - 1)/k1/p' <<< "$s"

Explanation: Stopping printing of lines by -n option in sed then in main program using regex ( - xi\*\*2 2\*xi - 1) to match as per requirement and if match is found printing k1 in output.

CodePudding user response:

Using sed

$ sed 's/( - \(xi\)\(\*\)\22   2\2\1 - 1)/k1/' <(echo "( - xi**2   2*xi - 1)")
  • Related