Search code examples
awkpattern-matchingtransposemultiline

awk transpose three patterns in tree into multiple lines


Hello do anyone might advice how to transpose this multiple lines which are in tree view with 3 patterns

listb: harold newu/edu
  tag: 05.8s
    step: sha256asd6f4, size: 1024
    step: sha256asd6f5, size: 1024
  tag: 06.8s
    step: sha256asd6f8, size: 1024

listb: break version
  tag: 05.8s
    step: sha256asd6c5, size: 720

listb: version/test
  not exist

which i need to align into following output

listb: harold newu/edu tag: 05.8s step: sha256asd6f4, size: 1024
listb: harold newu/edu tag: 05.8s step: sha256asd6f5, size: 1024
listb: harold newu/edu tag: 06.8s step: sha256asd6f8, size: 1024
listb: break version  tag: 05.8s step: sha256asd6c5, size: 720
listb: version/test not exist

i tried this partial solution but it lacks for me 3rd matched pattern "step" awk transpose lines based on pattern and move (copy) remaining columns after


Solution

  • Thanks for editing your question to show what you've already tried (it makes it much easier to provide potential solutions); here is a 'simpler' approach based on the presence/absence of "step" and "not exist" in each 'block' and only two levels of indentation:

    awk 'BEGIN{OFS=" "} /^[[:alpha:]]/ {a = $0} /^  / && !/^   / {gsub(/^ {1,}/, "", $0); b = $0} /^    / {gsub(/^ {1,}/, "", $0); c = $0} /step/ {print a, b, c} /not exist/ {print a, b}' file
    listb: harold newu/edu tag: 05.8s step: sha256asd6f4, size: 1024
    listb: harold newu/edu tag: 05.8s step: sha256asd6f5, size: 1024
    listb: harold newu/edu tag: 06.8s step: sha256asd6f8, size: 1024
    listb: break version tag: 05.8s step: sha256asd6c5, size: 720
    listb: version/test not exist
    

    Nicer formatting:

    awk '
    BEGIN {
        OFS = " "
    }
    
    /^[[:alpha:]]/ {
        a = $0
    }
    
    /^  / && ! /^   / {
        gsub(/^ {1,}/, "", $0)
        b = $0
    }
    
    /^    / {
        gsub(/^ {1,}/, "", $0)
        c = $0
    }
    
    /step/ {
        print a, b, c
    }
    
    /not exist/ {
        print a, b
    }' file
    listb: harold newu/edu tag: 05.8s step: sha256asd6f4, size: 1024
    listb: harold newu/edu tag: 05.8s step: sha256asd6f5, size: 1024
    listb: harold newu/edu tag: 06.8s step: sha256asd6f8, size: 1024
    listb: break version tag: 05.8s step: sha256asd6c5, size: 720
    listb: version/test not exist