I have a YAML file which includes a stanza looks this:
admin::common::passwords: alice: password: '$6$oTQhLvN/4VFJPscD$8LYwUMSFi' bob: password: '$6$JKOtLF0wHeZfIskt$W/M5.ugDS'
If the shell variable $ACCOUNT contains the account name (alice, bob, etc), and $YAML is the filename of the YAML file, I can add a new entry with sed, like this. It inserts the new account directly under the "admin::common::passwords:" line, so I know it's in the correct stanza:
sed -i /'^admin::common::passwords:'/a"\ ${ACCOUNT}:\n password: '${ENCRYPTED_PASS}'" $YAML
I can find an existing account like this with awk. Again, this finds the stanza, then finds the account within that stanza (it's probably possible to do this all in awk, but I'm not good enough at awk, and this will do the job):
awk "BEGIN{RS=ORS="\n\n";FS=OFS="\n"}/admin::common::passwords:/" $YAML | grep -A1 "^[ ]*${ACCOUNT}:"
But to delete a line, the best I can come up with is this:
sed -i "/^ ${ACCOUNT}:/,+1d" $YAML
Which would delete any line "^ alice:" anywhere in the file, whether it's in the admin::common::passwords stanza or elsewhere.
I can't make any assumptions about the content of the file, except that it does contain exactly one admin::common:passwords stanza (if it did not, then it would have been created by another part of my script; that bit is easy).
So, my question is this: How can I improve this sed to say 'Search for "^ ${ACCOUNT}:" within the admin::common::passwords stanza, and delete that matching line as well as the line below it'?
(it doesn't have to be sed, of course; it may be that awk or even Perl are better suited to the task)