Merge lines between two patterns using sed

前端 未结 2 575
有刺的猬
有刺的猬 2021-01-04 23:14

I have an output file that looks like this:

HEADER 1:
server1 server2 server3
server4 server5 server6
server7 server8 server9
HEADER 2:

HEADER 1:
server10 s         


        
相关标签:
2条回答
  • 2021-01-04 23:38

    Using sed:

    sed '/HEADER 1/{n;:l N;/HEADER 2/b; s/\n//; bl}' input
    
    • n skips/prints the current line (HEADER 1), clears buffer
    • l is a label for looping (goto label)
    • N adds (appends) lines to buffer (preserving newlines)
    • /HEADER 2/b, where b is branch (without the label, it is break), break out when HEADER2 is seen
    • s/\n// removes the newlines in the buffer
    • bl jumps back to label l
    0 讨论(0)
  • 2021-01-04 23:57

    This shows how it could be done using awk
    You can download Gawk for Windows

    awk '/HEADER/ {printf "\n%s\n",$0;next} {printf "%s ",$0}' file
    
    HEADER 1:
    server1 server2 server3 server4 server5 server6 server7 server8 server9
    HEADER 2:
    
    HEADER 1:
    server10 server11 server12 server13 server14 server15 server16 server17 server18
    HEADER 2:
    
    0 讨论(0)
提交回复
热议问题