如何在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
相关产品推荐
相关产品推荐

