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

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

    I just solved this problem by sed. Even if this is a 7 years old question, someone may can here for help, so I am writing my solution by sed here:

    sed 'N;/^\n$/D;P;D;'
    
    0 讨论(0)
  • 2020-12-13 06:32
    grep -A1 . <yourfile> | grep -v "^--$"
    

    This grep solution works assuming you want the following:

    Input

    line1
    
    line2
    line3
    
    
    line4
    
    
    
    line5

    Output

    line1
    
    line2
    line3
    
    line4
    
    line5
    0 讨论(0)
  • 2020-12-13 06:34

    Use python:

    s = file("filename.txt").read()
    while "\n\n\n" in s: s = s.replace("\n\n\n", "\n\n")
    import sys
    sys.stdout.write(s)
    
    0 讨论(0)
  • 2020-12-13 06:36

    Actually, if you replace multiple newlines with a single newline, the output would be:

    something
    something else
    something else again
    

    You can achieve this by:

    sed /^$/d FILE
    
    0 讨论(0)
  • 2020-12-13 06:36

    This uses marco's solution on multiple files:

    for i in *; do FILE=$(cat -s "$i"); echo "$FILE" > "$i"; done
    
    0 讨论(0)
  • 2020-12-13 06:36

    Python, with regular expression:

    import re
    import sys
    sys.stdout.write(re.sub('\n{2,}','\n\n', sys.stdin.read()))
    
    0 讨论(0)
提交回复
热议问题