How can I replace multiple empty lines with a single empty line in bash?

后端 未结 14 2375
难免孤独
难免孤独 2020-12-13 06:14

I have a file that contains:

something



something else

something else again

I need a bash command, sed/grep w.e that will produce the fo

14条回答
  •  感动是毒
    2020-12-13 06:37

    Use awk:

    awk '{ /^\s*$/?b++:b=0; if (b<=1) print }' file
    

    Breakdown:

    /^\s*$/?b++:b=0
        - ? :       the ternary operator
        - /^\s*$/   matches a blank line
        - b         variable that counts consecutive blank lines (b++).
                    however, if the current line is non-blank, b is reset to 0.
    
    
    if (b<=1) print
        print if the current line is non-blank (b==0)
              or if there is only one blank line (b==1).
    

    By adjusting the regex, you can generalize it to other scenarios like squeezing multiple blank lines (">") in email: https://stackoverflow.com/a/59189823/12483961

提交回复
热议问题