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

后端 未结 14 2286
难免孤独
难免孤独 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

    A solution with awk, which replaces several blank lines with a single blank line:

    awk 'BEGIN{bl=0}/^$/{bl++;if(bl==1)print;else next}/^..*$/{bl=0;print}' myfile
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-13 06:40

    Usually, if I find that sed can't do something I need, I turn to awk:

    awk '
    BEGIN {
        blank = 0;
    }
    
    /^[[:blank:]]*$/ {
         if (!blank) {
              print;
         }
         blank = 1;
         next;
    }
    
    {
         print;
         blank = 0;
    }' file
    
    0 讨论(0)
  • 2020-12-13 06:40

    Pipelining it to |uniq may be solution (if other than empty lines don't duplicate)

    0 讨论(0)
  • 2020-12-13 06:41

    I take it that you'll probably want to remove lines that only have whitespace.

    That can be done with:

    sed /^[:space:]*$/d FILE
    
    0 讨论(0)
  • 2020-12-13 06:43

    If someone want use perl

    perl -00pe0 < file
    

    will do the same, as cat -s :)

    0 讨论(0)
提交回复
热议问题