使用命令sed将变量替换为正则表达式错误

时间:2023-01-01 20:13:05

When I learn the command about sed,I find this problem which I can't solve.The txt that I want handle is following:

当我学习关于sed的命令时,我发现这个我无法解决的问题。我想要处理的txt如下:

myBook:test yetongxue$ cat test.txt 
    def IsNonce_strSet(self):
        """
        判断随机字符串是否存在
        @return true 或 false
        """
        return self._values.has_key('nonce_str')

And this is my command and result:

这是我的命令和结果:

myBook:test yetongxue$ sed "s/return self._values.has_key\(\)/mark1 \1 mark2/g" test.txt 
    def IsNonce_strSet(self):
        """
        判断随机字符串是否存在
        @return true 或 false
        """
        mark1  mark2('nonce_str')

I am puzzled about the position of mark2, which should be after ('nonce_str'). Like this:

我很困惑mark2的位置,它应该在('nonce_str')之后。像这样:

mark1 ('nonce_str') mark2

mark1('nonce_str')mark2

Anybody can explain this? Thanks very much!

有人可以解释一下吗?非常感谢!

And Further,how can I white the regular expression so I can match the string only nonce_str. My command is:

而且,我怎样才能使正则表达式变白,这样我才能匹配字符串nonce_str。我的命令是:

sed "s/return self._values.has_key('()')/mark1 \1 mark2/g" test.txt

sed“s / return self._values.has_key('()')/ mark1 \ 1 mark2 / g”test.txt

But it's not working.

但它不起作用。

1 个解决方案

#1


4  

The regular expression \(\) matches and captures an empty string in sed.

正则表达式\(\)匹配并捕获sed中的空字符串。

Apparently, you expect to capture a set of literal parentheses and the text between them?

显然,您希望捕获一组字面括号和它们之间的文本?

sed ´s/return self\._values\.has_key\(([^()]*)\)/mark1 \1 mark2/'

#1


4  

The regular expression \(\) matches and captures an empty string in sed.

正则表达式\(\)匹配并捕获sed中的空字符串。

Apparently, you expect to capture a set of literal parentheses and the text between them?

显然,您希望捕获一组字面括号和它们之间的文本?

sed ´s/return self\._values\.has_key\(([^()]*)\)/mark1 \1 mark2/'