3

In a bash script I have to append a line into a systemd file. The file looks like this:

[Unit]
...

[Service]
...

The line must be appended under the [Unit] section and after all the lines in this section:

[Unit]
...
---MY LINE--- 

[Service]
...

I know how to append the line directly after [Unit]:

[Unit]
---MY LINE---
...

[Service]
... 

with sed like this:

$ sed '/\[Unit\]/a ---MY LINE---' input_file

but how can I append my line after all the lines in the section?

1 Answers1

4

If you have GNU awk in your system, you can use the following script. It appends the string right before the start of the next section.

awk -v RS='\\[[^]]*\\]' '{printf $0; if(oRT~/Unit/){print "---MY LINE---"}; printf RT; oRT=RT}' input_file

RS is the record separator. It is a regex set to anything between square bracket, such that it matches both [Unit] and [Service]. Having such a RS allows to have a record with the full content of a block section.

RT is the record terminator. It is set dynamically by awk for each record based on RS. It will hold successively [Unit] and [Service].

The trick is to store the record terminator in the variable oRT. If this one has the word Unit then append the wanted string ---MY LINE---.


If you want to append the string before the empty line at the end of the section use the following script:

awk -v RS='\\[[^]]*\\]' 'oRT~/Unit/{sub(/\n$/,"---MY LINE---\n\n")}{printf $0 RT; oRT=RT}' input_file

The sub function replaces the empty line at the end of the record by appending the wanted string and an empty line.

oliv
  • 371
  • 1
  • 5