I have command output like
var="""
Name=<Some name>
key1=value1
key2=value2 key3=value3
key4=value4
Name=<Some other name>
key1=val1
key2=val2 key3=val3
key4=val4
"""
See e.g. the output of scontrol show partition.
From these multiline strings, how do I extract a certain key value pair?
I can e.g. use sed to match a block via
echo "${var}" | | sed -n '/^Name=/,/^\s+key4=/p'
This gives me the entire block (nothing is gained here)
How do I get output like
<Some name>: key4=value4
<Some other name>: key4=val4
or
<Some name>: key3=value3
<Some other name>: key3=val3
EDIT in response to comments
i.e. print the Name of the block together with the value of the specified key.
Moreover one can assume:
- Key and value are separated by
= - Key value pairs are separated by
- Keys or values do not contain white spaces or new lines
- Keys do not appear in values
Some explanations about the comment, how it works
From command line help
perl -hhere 0 special case "paragraph mode" (Two or more consecutive newline characters will act as the record separator).
About the expression, the if modifier is shorter one-line in this case but, is the same as
About the regex the capturing groups
(.*)are matching any character except newline.Thesflag inside non-capturing group(?s:..)changes the meaning of.to also match newline. Themflag to allow^to match also the position after a newline.About backtracking, because of the multiple
*quantifiers, the regular expression may have a catastrophic backtracking, some more quantifiers to prevent backtracking, the regex can be improved:(?:..): non-capturing group