使用 sed 在特定块的大括号之前添加新行

  • 本文关键字:新行 添加 sed 使用 regex sed
  • 更新时间 :
  • 英文 :


我的python代码看起来像这样:

def one():
#lines of code
context = {
#lines of code
}
def two():
#lines of code
context = {
#lines of code
}
context.up({ #lines 
})

我想在函数二的上下文部分添加"一些新行",就在右大括号之前,如下所示:

def one():
#lines of code
context = {
#lines of code
}
def two():
#lines of code
context = {
#lines of code
Some new line
}
context.up({ #lines 
})

如何使用 sed 执行此操作?

我尝试了以下命令:

sed -i '/^def two.*context={/,/^[[:space:]]}/{s/^([[:space:]]*)}/1some new linen&/;}' file

但它似乎没有任何变化。

这可能对你有用(GNU sed(:

sed '/def two/,/^s*context>/!b;/^s*context>/!b;:a;n;/^s*}/!ba;i some new line' file

将范围限制为def two,并在context内读取行,直到结束}并插入新行。

第一个 sed 指令是一个正则表达式范围,即如果行不在def twocontext之间,则像往常一样打印它们,但不要使用任何 sed 指令进一步处理它们(b表示中断任何进一步的命令(。同样,下一个正则表达式会忽略除包含context之外的任何行。从此地址打印图案空间 (PS( 中的当前行,并用下一行 (n( 填充 PS。如果该行不包含}则跳回(ba(到位置:a。否则插入(i(一些新文本,然后打印PS的内容。

要保留缩进,请使用:

sed '/def two/,/^s*contextb/!b;/^s*contextb/!b;:a;n;/^s*}/!h;//!ba;x;s/S+.*/some new line with indent/p;g' file

最新更新