简体   繁体   English

sed - 在匹配后 X 行后插入行

[英]sed - insert line after X lines after match

I have the following contents:我有以下内容:

void function_1()
{
    //something (taking only 1 line)
}
->INSERT LINE HERE<-
//more code

Using sed, I want to insert line at the INSERT LINE HERE label.使用 sed,我想在 INSERT LINE HERE 标签处插入行。 The easiest way should be:最简单的方法应该是:

  1. find text "function_1"查找文本“function_1”
  2. skip 3 lines跳过 3 行
  3. insert new line插入新行

But none of the known sed options do the job.但是没有一个已知的 sed 选项可以完成这项工作。

sed '/function_1/,3a new_text

inserts new_text right after 'function_1'在“function_1”之后立即插入 new_text

sed '/function_1/,+3a new_text

inserts new_text after each of the next 3 lines, following 'function_1'在接下来的 3 行中的每一行之后插入 new_text,在 'function_1' 之后

sed '/function_1/N;N;N; a new_text

inserts new_text at multiple places, not related to the pattern在多个位置插入 new_text,与模式无关

Thanks.谢谢。

Try this with GNU sed:用 GNU sed 试试这个:

sed "/function_1/{N;N;N;a new_text
}" filename
sed '/function_1(/,/^[[:space:]]*}/ {
 ,/^[[:space:]]*}/ a\
Line that\
you want to\
insert (append) here
   }' YourFile
  • insert the line after the } (alone in the line with eventually some space before) from the section starting with function_1(插入后的行} (独自一人在符合最终一些前空间)从开始与部分function_1(
  • i assume there is no } alone in your internal code like in your sample我假设您的内部代码中没有单独的}就像您的示例

be carreful on selection based on function name because it could be used (and normaly it is) as a call to the function itself in other code section so maybe a /^void function_1()$/ is better小心根据函数名称进行选择,因为它可以(通常是)用作其他代码部分中对函数本身的调用,因此/^void function_1()$/可能更好

Use awk:使用 awk:

awk '1;/function_1/{c=4}c&&!--c{print "new text"}' file
  • 1 is a shorthand for {print} , so all lines in the file are printed 1{print}的简写,所以文件中的所有行都被打印出来
  • when the pattern is matched, set c to 4当模式匹配时,将c设置为 4
  • when c reaches 1 (so c is true and !--c is true), insert the linec达到 1(所以c为真且!--c为真)时,插入该行

You could just use !--c but adding the check for c being true as well means that c doesn't keep decreasing beyond 0.你可以只使用!--c ,但增加了对检查c是和手段,真正的c不会继续下降超过0。

Don't count, match:不计算,匹配:

sed -e '/^void function_1()/,/^}$/ { /^}$/a\
TEXT TO INSERT
}' input

This looks at the block between the declaration and the closing brace, and then append TEXT_TO_INSERT after the closing brace.这会查看声明和右大括号之间的块,然后在右大括号之后附加 TEXT_TO_INSERT。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM