How can I use a regex variable for a find and replace command in bash?

这一生的挚爱 提交于 2020-12-13 04:39:28

问题


This is a follow-up to a previous question I had asked. For that question, I received an excellent answer by @markp-fuso demonstrating the use of an array of search patters for sed to perform a particular substitution task.

In this question, I would like to perform the same find and replace task of replacing all forms of pow(var,2) with square(var) but I would like to do this by using a regex variable.

The sample input and output files are below:

InputFile.txt:

pow(alpha,2) + pow(beta,2)
(3*pow(betaR_red,2))
2/pow(gammaBlue,3))
-pow(epsilon_gamma,2)+5

OutputFile.txt:

square(alpha) + square(beta)
(3*square(betaR_red))
2/pow(gammaBlue,3))
-square(epsilon_gamma)+5

After looking at this answer and some more tinkering on https://regex101.com/r/80Hp5Z/1/, I was able to describe the text between pow( and ,2) using (?<=pow\().*?(?=,2\)).

Using Bash, I am trying to form a two command solution where:

  1. First command sets var to (?<=pow\().*?(?=,2\))
  2. Second command performs sed "s/pow(${var},2)/square(${var})/g" InputFile.txt > OutputFile.txt

It seems once I figure out how to set var successfully in Step 1, I can proceed with the command in Step 2. However, after reading this question and this question I tried the following two commands but they did not perform any substitutions:

bash$ var="(?<=pow\().*?(?=,2\))"
bash$ sed "s/pow(${var},2)/square(${var})/g" InputFile.txt > OutputFile.txt

I would really appreciate some help forming a 2-command Bash solution as described above that makes use of a regex variable and transforms InputFile.txt into OutputFile.txt.


回答1:


If you want to deal with parentheses in squared expressions, try:

One-line Solution:

perl -pe 's/pow\s*\((([^()]|\((?2)+\))+)\s*,\s*2\s*\)/square($1)/g' inputFile.txt

Two-Line Solution:

REGEX="pow\s*\((([^()]|\((?2)+\))+)\s*,\s*2\s*\)"
perl -pe "s/$REGEX/square(\1)/g" inputFile.txt

https://regex101.com/r/Dp0Duf/1.




回答2:


You may use this sed with one capture group:

s='pow(\([^)]+),2\)'
sed -E "s/$s/square\1)/g" file
square(alpha) + square(beta)
(3*square(betaR_red))
2/pow(gammaBlue,3))
-square(epsilon_gamma)+5

RegEx Demo



来源:https://stackoverflow.com/questions/64187160/how-can-i-use-a-regex-variable-for-a-find-and-replace-command-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!