You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

逻辑说明

  1. 匹配到this is summer.时,设置flag=1(开启替换模式)
  2. 匹配到其他季节行(this is 开头但非summer)时,设置flag=0(关闭替换模式)
  3. 只要flag=1,就用gsub替换当前行的cotton为light color
  4. 最后的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:55:20