'Using sed to substitute mathematical expressions
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.
Solution 1:[1]
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.
Solution 2:[2]
Using sed
$ sed 's/( - \(xi\)\(\*\)\22 + 2\2\1 - 1)/k1/' <(echo "( - xi**2 + 2*xi - 1)")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RavinderSingh13 |
| Solution 2 | HatLess |
