如何用sed或awk匹配summer后修改对应行的cotton为light color
解决方案
原始文件内容
$ cat sample1.txt this is about weather. this is summer. I drink cold coffee I eat Ice-cream I wear cotton clothes. this is winter I drink hot coffee I eat cake I wear warm clothes. this is summer. I wear cotton sleeveless. I drink juice.
使用sed实现
直接利用sed的区间匹配+替换功能,精准覆盖summer之后到下一个季节之前的内容:
sed '/this is summer\./,/this is /s/cotton/light color/' sample1.txt
逻辑说明
/this is summer\./,/this is /:定义匹配区间——从包含this is summer.的行开始,到下一个以this is开头的季节行结束s/cotton/light color/:在上述区间内,将所有cotton替换为light color
使用awk实现
通过标志位控制替换开关,逻辑更灵活,可适配更复杂的场景:
awk '/this is summer\./ {flag=1} /this is / && !/summer/ {flag=0} flag {gsub(/cotton/, "light color")} 1' sample1.txt
逻辑说明
- 匹配到
this is summer.时,设置flag=1(开启替换模式) - 匹配到其他季节行(
this is开头但非summer)时,设置flag=0(关闭替换模式) - 只要
flag=1,就用gsub替换当前行的cotton为light color - 最后的
1表示打印所有行(无论是否修改)
替换后效果
执行上述命令后,文件内容会变成:
this is about weather. this is summer. I drink cold coffee I eat Ice-cream I wear light color clothes. this is winter I drink hot coffee I eat cake I wear warm clothes. this is summer. I wear light color sleeveless. I drink juice.
内容的提问来源于stack exchange,提问作者meg
相关产品推荐
相关产品推荐

