使用sed替换字符串之间的文本

时间:2018-01-03 09:11:44

标签: sed

我尝试使用sed替换文件中的a.mysql.com以获取以下行

    'ENGINE': 'a.mysql.com', # MySQL host

如何在不删除评论条目的情况下替换文本?

我尝试了以下但是它没有工作

sed -i -e "s/\('ENGINE': ').*\([^']*\)/\1new.mysql.com\2/g" file.py

2 个答案:

答案 0 :(得分:1)

关注sed可能对您有帮助。

sed "s/\(.*: \)\('.*'\)\(.*\)/\1'my_next_text'\3/"   Input_file

输出如下。

'ENGINE': 'my_next_text', # MySQL host

编辑: 使用已编辑的OP输入文件对其进行测试,如下所示。

cat Input_file
    'ENGINE': 'a.mysql.com', # MySQL host

sed "s/\(.*: \)\('.*'\)\(.*\)/\1'my_next_text'\3/" Input_file
    'ENGINE': 'my_next_text', # MySQL host

EDIT2: 如果OP想要检查其中包含字符串ENGINE的行,则可以执行以下操作。

sed "/    'ENGINE/s/\(.*: \)\('.*'\)\(.*\)/\1'my_next_text'\3/"   Input_file

答案 1 :(得分:1)

您可以使用GNU sed使用以下逻辑来满足您的要求。

sed "/ENGINE/s/'[^']*'/'new.mysql.com'/2" file 

s/ENGINE/匹配包含ENGINE的所有行,并执行以下替换s/'[^']*'/'new.mysql.com'/2

s/                # Substitute  
'                 # Match a single quote
[^']*             # Match anything not a single quote 
'                 # Match the closing single quote 
/                 # Replace with 
'new.mysql.com'   # The literal value
/2                # The 2 here matches the second quoted string, not the first. 

在适当修改文件后添加-i扩展名。