将sed与regex和( [英] Use sed with regex and (
问题描述
我在php文件中有一个功能:
I have a function in php file:
_t('', 'Award received')
我制作了一个正则表达式,它找到了函数_t(''
I've made a regex, which finds first part of the function _t(''
现在,我想将该功能替换为其他功能(实际上,我想向该功能添加参数).
Now, I want to replace that function with something else (actually, I want to add argument to the function).
从控制台:
grep -rl "_t('', 'Award received')" application | xargs sed -i "s/_t\s*\(\s*['|\"](\s*\s*)['|\"]/test/g"
Sed不想进行替换,它说:((或(不带一对),因此看起来它正在尝试在正则表达式中寻找括号...
Sed doesn't want to make replacement, it says: "( or ( without a pair", so it looks like it is trying to look for bracket inside regex...
如何将sed与包含方括号的正则表达式一起使用?
How can I use sed with regex expressions containing brackets?
我有要替换的测试字符串:
I have test string which I want to replace:
_t('124', 'Test')
当我进行简单替换时
sed -i -E 's/124JHGJH/124/g'
它工作正常.
但是,如果我尝试用括号等替换整个字符串,它只会挂出并且没有响应...
But if I try to replace whole string, with parenthesis and other, it just hangs out and not responding...
sed -i -E 's/_t\(\'124JHGJH\'/124/g'
推荐答案
请注意sed正则表达式中 \(
和(
)之间的区别.
Take note of the difference between \(
and (
in sed regex.
要在函数调用的最后添加新参数:
To add a new parameter at then end of the function call:
echo "_t('', 'Award received')" | sed 's/_t([^)]\+/&, new_param/'
_t('', 'Award received', new_param)
正则表达式为:
-
-t(
=文字字符 -
[^)] \ +
=一个或多个非<)
字符
-t(
= literal characters[^)]\+
= one or more non-)
characters
下一个字符将是函数的关闭括号,因此我假设您要在其中插入新参数.我在替换中使用&
将与正则表达式匹配的文本放在其位置.
The next character will be the function's close paren, so that's where I assume you want to insert the new parameter. I use &
in the replacement to put the text matched by the regex in its place.
如果存在一个包含紧密括号字符的文字字符串参数,这将中断.
This will break if there's a literal sting argument that contains a close paren character.
这篇关于将sed与regex和(的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!