awksed

How to merge multiline grep output to a single line in linux


I have below output that have gathered by doing cat interim_detailed_cert | grep -E "Label :|dNSName:".

Output

Label : cert1
        dNSName: dns1.1
        dNSName: dns1.2
Label : cert2
        dNSName: dns2.1 
Label : cert3
        dNSName: dns3.1
        dNSName: dns3.2

From above, I'm trying to filter only the dNSName value, in a single line (if there are two values) separated by a comma ,

Expected output

dns1.1, dns1.2
dns2.2
dns3.1, dns3.2

Any suggestion on this will be helpful. Thanks


Solution

  • Given your example I would harness GNU AWK for this task following way, let command output be

    Label : cert1
            dNSName: dns1.1
            dNSName: dns1.2
    Label : cert2
            dNSName: dns2.1 
    Label : cert3
            dNSName: dns3.1
            dNSName: dns3.2
    

    then

    command | awk 'BEGIN{RS="\n[^[:space:]]";OFS=", ";FPAT="dns[0-9.]+"}{$1=$1;print}'
    

    gives output

    dns1.1, dns1.2
    dns2.1
    dns3.1, dns3.2
    

    Explanation: I inform GNU AWK that records are separated by newline (\n) followed by non-white-space character, i.e. records are split at 1st character of every line which does not start with white-space character, that fields in output should be separated by comma followed by space, that fields are constituted by dns followed by one-or-more (+) digits or dots. I use $1=$1 to trigger string rebuilt and print to output line after change.

    (tested in GNU Awk 5.1.0)