如何从路由字符串中找到模式并在bashshell中编辑下一行


cat test.txt
baseurl=http://repo.mysql.com/yum/mysql-5.5-community/el/7/$basearch/
enabled=0  

上面是目标文件test.txt。我需要找到模式baseurl=http://repo.mysql.com/yum/mysql-5.5-community/el/7/$basearch/,将下一行enabled=0替换为enabled=1

我尝试了sed '@baseurl=http://repo.mysql.com/yum/mysql-5.5-community/el/7/$basearch/@!b;n;cenabled=1' test.txt,但失败了。

注意:不能使用@等其他delimeter而不是/,因为这不是替换命令。

提前感谢!

如果您对awk满意,请尝试以下操作。

awk '
/baseurl=http://repo.mysql.com/yum/mysql-5.5-community/el/7/$basearch//{
print
flag=1
next
}
flag && /enabled/{
print "enabled=1"
flag=""
next
}
1
'  Input_file

如果您想将输出保存到Input_file本身,请在上面的代码中附加> temp_file && mv temp_file Input_file

这可能会奏效—它找到"baseurl=",然后抓住下一行,用"enabled=1"替换"enabled=0":

sed '/baseurl=/ {N;s/enabled=0/enabled=1/;}' test.txt

请随意将初始正则表达式更改为您提到的行。我只是想展示一下一般的解决方案。

我希望这能有所帮助!

sed -E '/baseurl=http://repo.mysql.com/yum/mysql-5.5-community/el/7/$basearch//!b;n;cenabled=1' test.txt > temp_file && mv temp_file  test.txt

这个答案来自RavinderSingh13和WiktorStribiżew,我只是同意它。

最新更新