简体   繁体   English

使用sed命令在[stuff]之后添加行

[英]Append line after [stuff] using the sed command

Effectively I am trying to insert a line of text directly after a stanza heading in a configuration file "testfile" kind of like this: 实际上,我试图在配置文件“ testfile”中的节标题之后直接插入一行文本,如下所示:

[default]

[stuff]

[stuff_test]

[end]

The goal is to insert a line of text "variable = 1" directly after and only after [stuff]. 目标是在[stuff]之后和之后直接插入一行“ variable = 1”文本。 This is the desired output of "testfile" 这是“ testfile”的所需输出

[default]

[stuff]
variable = 1

[stuff_test]

[end]

When I try using the append function of sed: 当我尝试使用sed的append函数时:

sed -i "/[stuff]/ a variable = 1" testfile

I get the following: 我得到以下内容:

[default]
variable = 1

[stuff]
variable = 1

[stuff_test]
variable = 1

[end]

My question is why is it inserting text in the first three stanzas and not just the second stanza as I intended? 我的问题是为什么要在前三个节中插入文本,而不仅仅是在我想要的第二个节中插入文本? I tried using exact match but I might have the context wrong? 我尝试使用完全匹配,但上下文可能错误? The following other efforts have been tried: 尝试了以下其他措施:

sed -i "/\<[stuff]\>/ a variable = 1" testfile

sed "/\<\[stuff\]\>/ a variable = 1" testfile

This will not insert any text into the file. 这不会在文件中插入任何文本。 How do I get sed to insert only after the "[stuff]" stanza? 如何仅在“ [stuff]”节之后插入sed?

The address /[stuff]/ is interpreted as a regular expression, ie, matches any line that contains any of the characters s , t , u or f . 地址/[stuff]/被解释为正则表达式,即,与包含stuf任意字符s任何行匹配。 To avoid interpretation as a bracket expression, you have to escape the square brackets: 为了避免将其解释为方括号表达式,您必须转义方括号:

sed -i "/\[stuff\]/ a variable = 1" testfile

with awk awk

awk 'NF > 0 && $0 ~ /\[stuff\]/{$0=$0RS"variable = 1"} 1' file

check if NF: number of field is greater than zero and matched stuff regex , then append the line with RS: record seperator , which is newline with expected value 检查NF: number of field是否大于零并匹配stuff regex ,然后在该行后附加RS: record seperator ,这是具有期望值的换行符

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

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