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

如何在Shell脚本中于文件指定字符串前插入多行内容

在指定行前插入多行代码的正确sed用法

现有log.txt内容

properties{
set properties()
}

buildPipeline()
defPipeline(){
execute()
}

需要插入的代码

要在buildPipeline()之前插入以下代码:

def testbranch= 'feature'
if(env.BRANCH_NAME.startswith(testbranch)){
properties([pipelinetriggers([cron('0 */2 * * 1-5')]),])
}

错误尝试分析

你之前用的sed -i -e "$a..."命令中,$代表文件最后一行,a是在指定行之后追加内容,所以所有代码都被插到了文件末尾,不符合需求。

正确解决方案

使用sed的匹配功能定位到buildPipeline()行,用i命令在该行之前插入多行内容,单条命令即可完成:

GNU sed(Linux环境)

sed -i '/^buildPipeline()/i\def testbranch= '\''feature'\''\
if(env.BRANCH_NAME.startswith(testbranch)){\
properties([pipelinetriggers([cron('\''0 */2 * * 1-5'\'')]),])\
}' log.txt

macOS sed(BSD环境)

macOS的sed语法略有差异,需要在每行插入内容前都加反斜杠:

sed -i '' '/^buildPipeline()/i\
def testbranch= '\''feature'\''\
if(env.BRANCH_NAME.startswith(testbranch)){\
properties([pipelinetriggers([cron('\''0 */2 * * 1-5'\'')]),])\
}' log.txt

执行后输出

运行上述命令后,log.txt内容将变为:

properties{
set properties()
}
def testbranch= 'feature'
if(env.BRANCH_NAME.startswith(testbranch)){
properties([pipelinetriggers([cron('0 */2 * * 1-5')]),])
}
buildPipeline()
defPipeline(){
execute()
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:45:11