In a file I want to append a string after the specific segment with key "sys-mgmt-agent".
This is the file content:
sys-mgmt-agent:
networks:
edgex-network:
aliases:
- edgex-sys-mgmt-agent
depends_on:
- redis
volumes:
- /proc/uptime:/proc/uptime
- /var/log/auth.log:/var/log/auth.log
- ${HOST_SECURITY_FILE_PATH}edgex-redis:/tmp/edgex/secrets/edgex-redis:z
edge-orchestrator:
networks:
edgex-network:
aliases:
- edgex-sys-mgmt-agent
depends_on:
- redis
volumes:
- /proc/uptime:/proc/uptime
- /var/log/auth.log:/var/log/auth.log
- ${HOST_SECURITY_FILE_PATH}edgex-redis:/tmp/edgex/secrets/edgex-redis:z
This is the expected result:
sys-mgmt-agent:
networks:
edgex-network:
aliases:
- edgex-sys-mgmt-agent
depends_on:
- redis
volumes:
- /proc/uptime:/proc/uptime
- /var/log/auth.log:/var/log/auth.log
- ${HOST_SECURITY_FILE_PATH}edgex-redis:/tmp/edgex/secrets/edgex-redis:z
MY STRING
edge-orchestrator:
networks:
edgex-network:
aliases:
- edgex-sys-mgmt-agent
depends_on:
- redis
volumes:
- /proc/uptime:/proc/uptime
- /var/log/auth.log:/var/log/auth.log
- ${HOST_SECURITY_FILE_PATH}edgex-redis:/tmp/edgex/secrets/edgex-redis:z
I found the segment using sed command: sed -n '/sys-mgmt-agent:/,/^s*$/p' <file>
but I can’t append my string.
3
Answers
Assumptions:
bash
sys-mgmt-agent:
shows up more than once the desired string is to be appended to each segmentOne
awk
solution:The above generates:
A
sed
idea that builds on OPssed
attempt:Where:
/sys-mgmt-agent/,/^$/
– range to search for{...}
– commands to apply to matching range/^$/i ${mystring}
– at the blank line insert a new line " MY STRING"NOTE: The
i ${mystring}
can’t have anything after it on the same line hence the 2-line solution; I’m open to suggestions on how to collapse this into a single line.UPDATE: @potong’s suggestion for using
-e
flags to piece together a one-line solution works with the addition of double quotes around${mystring}
:The above generates:
This might work for you (GNU sed):
N.B. if
MY STRING
contains/
‘s these must be escaped/quoted i.e./
. This also indents to the depth of the last stanza.