user3614014 user3614014 - 5 months ago 27
Linux Question

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:

[default]

[stuff]

[stuff_test]

[end]


The goal is to insert a line of text "variable = 1" directly after and only after [stuff]. This is the desired output of "testfile"

[default]

[stuff]
variable = 1

[stuff_test]

[end]


When I try using the append function of sed:

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. Please help! How do I get sed to insert only after the "[stuff]" stanza?

Answer

The address /[stuff]/ is interpreted as a regular expression, i.e., matches any line that contains any of the characters s, t, u or f. To avoid interpretation as a bracket expression, you have to escape the square brackets:

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