如何在 bash 中使用正则表达式变量进行查找和替换命令? [英] How can I use a regex variable for a find and replace command in bash?
问题描述
这是我之前提出的问题的后续.对于那个问题,我收到了@markp-fuso 的出色回答,演示了如何使用 sed
的搜索模式数组来执行特定的替换任务.
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.
在这个问题中,我想执行相同的查找和替换任务,用 square(var)
替换所有形式的 pow(var,2)
但我想通过使用正则表达式变量来做到这一点.
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
在查看了这个答案之后,对https://regex101.com/r/80Hp5Z/1/,我能够描述pow(
和,2)
使用 (?<=pow\().*?(?=,2\))
.
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\))
.
使用 Bash,我试图形成一个两个命令的解决方案,其中:
Using Bash, I am trying to form a two command solution where:
- 第一个命令将
var
设置为(?<=pow\().*?(?=,2\))
- 第二个命令执行
sed "s/pow(${var},2)/square(${var})/g";输入文件.txt输出文件.txt
似乎一旦我弄清楚如何在步骤 1 中成功设置 var
,我就可以继续执行第 2 步中的命令.但是,在阅读此问题后 和这个 问题 我尝试了以下两个命令,但他们没有执行任何替换:
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
我真的很感谢帮助形成如上所述的 2 命令 Bash 解决方案使用正则表达式变量并将 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
.
推荐答案
如果你想处理平方表达式中的括号,试试:
If you want to deal with parentheses in squared expressions, try:
单行解决方案:
perl -pe 's/pow\s*\((([^()]|\((?2)+\))+)\s*,\s*2\s*\)/square($1)/g' inputFile.txt
双线解决方案:
REGEX="pow\s*\((([^()]|\((?2)+\))+)\s*,\s*2\s*\)"
perl -pe "s/$REGEX/square(\1)/g" inputFile.txt
https://regex101.com/r/Dp0Duf/1.
这篇关于如何在 bash 中使用正则表达式变量进行查找和替换命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!