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

如何用sed替换inlet花括号内带type行的patch为wall

需求

将代码中inlet块内的type patch;替换为type wall;,outlet块内内容保持不变。

原始代码

inlet
{
    type    patch;
    ...
}
outlet
{
        type  patch;
} 

目标代码

inlet
{
    type    wall;
    ...
}
outlet
{
        type  patch;
} 

现有尝试的问题

  1. 执行命令:

    echo "inlet { patch } outlet" | sed "/^\(inlet [^ ]*\) .* \([^ ]*\)$/s//\1 wall \2/"
    

    输出缺失右花括号:

    inlet { wall outlet
    
  2. 执行命令:

    echo "inlet {patch} outlet {patch}"| sed "/inlet/,/outlet/{s/patch/wall/}"
    

    该命令会替换inlet到outlet范围内所有的patch,无法限制仅替换type行的内容。

解决方案

使用sed的地址范围匹配结合模式匹配,仅在inlet块内的type行替换patch为wall:

sed '/^inlet$/,/^}/ { /type.*patch/s/patch/wall/ }' your_file.txt

命令解释

  • /^inlet$/,/^}/:匹配从inlet行开始到对应的闭合花括号行的整个代码块
  • { /type.*patch/s/patch/wall/ }:在上述范围内,仅对包含type且带有patch的行执行替换操作

这样就能精准修改inlet块内的目标行,同时保留outlet块的内容不变。

内容的提问来源于stack exchange,提问作者nipinl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:29:56