how to find continuous blank lines and convert them to one

Viewed 347

I have a file -- a, and exist some continues blank line(more than one), see below:

cat a
1

2


3



4

5

So first I want to know if exist continues blank lines, I tried

cat a | grep '\n\n\n'

nothing output. So I have to use below manner

vi a 
:set list
/\n\n\n

So I want to know if exist other shell command could easily implement this? then if exist two and more blank lines I want to convert them to one? see below

1

2

3

4

5

at first I tried below shell

sed 's/\n\n\(\n\)*/\n\n/g' a

it does not work, then I tried this shell

cat a | tr '\n' '$' | sed 's/$$\(\$\)*/$$/g' | tr '$' '\n'

this time it works. And also I want to know if exist other manner could implement this?

6 Answers

remark: This is a copy from my answer here


A very quick way is using

awk 'BEGIN{RS="";ORS="\n\n"}1' 

How does this work:

knowns the concept records (which is by default lines) and you can define a record by its record separator RS. If you set the value of RS to an empty string, it will match any multitude of empty lines as a record separator. The value ORS is the output record separator. It states which separator should be printed between two consecutive records. This is set to two <newline> characters. Finally, the statement 1 is a shorthand for {print $0} which prints the current record followed by the output record-separator ORS.

note: This will, just as cat -s keep lines with only blanks as actual lines and will not suppress them.

Related