0

I need to find a way to add a line to files after a pattern, but I don't want to edit the line the pattern is on.

For example, my original file will look something like

group: misc
host: server1
job: internal

and I'd like to get it to something like

group: misc
host: server1
role: webserver
job: internal

The difficulty is i need to match on "host:" but the name after host will be different every time. I haven't found a way for sed to respect the rest of the line, and instead dumps the new lines immediately after finding "host:" leaving the hostname orphaned after the new line.

2
  • 1
    Is the original file in a structured format such as YAML? If it is, then the order is not important, and adding a new key+value is a s easy as yq -y --arg role "webserver" '. += $ARGS.named' file (using yq and with -i added, you get in-place edit).
    – Kusalananda
    Jul 8, 2022 at 16:16
  • yeah, if this is yaml, then sed (and regexes in general) are the wrong tool, and you should use a yaml parser Jul 8, 2022 at 16:49

4 Answers 4

5

append text after a match:

sed '/^host: /a\
role: webserver
' sample

Or insert a line before a match:

sed '/^job: /i\
role: webserver
' sample
2

Similarly to Marcus's answer, replace the end of line ($) with a a newline and the line you want to insert on lines that start with host::

$ sed '/host: / s/$/\nrole: webserver/ ' file
group: misc
host: server1
role: webserver
job: internal

This will require GNU sed (or any other sed implementation that supports it) for the \n on the right-hand side. If the above fails, try:

$ sed '/host: / s/$/\
role: webserver/' file
group: misc
host: server1
role: webserver
job: internal
1

Sure, this is a pretty basic regex: use .* to match everything, an arbitrary amount of times; since sed is line-based, anyways, that only works till the end of each line.

So, your full GNU sed call is

sed 's/^host: .*$/&\nrole: webserver/'
1

Using sed

$ sed '/^host.*/{p;s//role: webserver/}' input_file
group: misc
host: server1
role: webserver
job: internal

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .