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

时间:2018-11-01 17:28:21

标签: sed

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,但失败了。

  

注意:不能使用其他分隔符,例如@而不是/,因为   这不是替换命令。

谢谢!

3 个答案:

答案 0 :(得分:0)

如果您对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

答案 1 :(得分:-1)

这可能会解决-它找到'baseurl =',然后获取下一行,并将'enable = 0'替换为'enabled = 1':

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

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

我希望这会有所帮助!

答案 2 :(得分:-1)

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,我很喜欢。