Daniel
Daniel

Reputation: 2726

Merge two blank lines into one

I am looking for a solution of turning file A to file B, which requires merging two blank lines into one.

File-A:

// Comment 1
// Comment 2

// Comment 3


// Comment 4



// Comment 5

File-B:

// Comment 1
// Comment 2

// Comment 3

// Comment 4

// Comment 5

From this post, I know how to delete empty lines, I am wondering how to merge two consecutive blank lines into one.

PS: blank means that it could be empty OR there might be a tab or a space in the line.

Upvotes: 5

Views: 2120

Answers (6)

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed '$!N;s/^\s*\n\s*$//;P;D' file

This will convert 2 blank lines into one.

If you want to replace multiple blank lines into one:

sed ':a;$!N;s/^\s*\n\s*$//;ta;P;D' file

On reflection a far simpler solution is:

sed ':a;N;s/\n\s*$//;ta' file

Which squeezes one or more blank lines to a single blank line.

An even easier solution uses the range condition:

sed '/\S/,/^\s*$/!d' file

This deletes any blank lines other than those following a non-blank line.

Upvotes: 6

glenn jackman
glenn jackman

Reputation: 246847

awk -v RS='([[:blank:]]*\n){2,}' -v ORS="\n\n" 1 file

I had hoped to produce a shorter Perl version, but Perl does not use regular expressions for its record separator.

awk does not edit in-place. You would have to do this:

awk -v RS='([[:blank:]]*\n){2,}' -v ORS="\n\n" 1 file > tmp && mv tmp file

Upvotes: 0

Jotne
Jotne

Reputation: 41456

Here is a simple solution with awk:

awk '!NF && !a++; NF {print;a=0}' file
// Comment 1
// Comment 2

// Comment 3

// Comment 4

// Comment 5

NF counts the number of fields; note that a line composed entirely of spaces and tabs counts as a blank line, too.
a is used to count blank lines, and if it's more than 1, skip it.

Upvotes: 4

Barmar
Barmar

Reputation: 781131

sed -r 's/^\s+$//' infile | cat -s > outfile

sed removes any whitespace on a blank line. The -s option to cat squeezes consecutive blank lines into one.

Upvotes: 6

jimm-cl
jimm-cl

Reputation: 5422

This page might come handy. TL;DR as follows:

# delete all CONSECUTIVE blank lines from file except the first; also
# deletes all blank lines from top and end of file (emulates "cat -s")
sed '/./,/^$/!d'          # method 1, allows 0 blanks at top, 1 at EOF
sed '/^$/N;/\n$/D'        # method 2, allows 1 blank at top, 0 at EOF

Upvotes: 1

Lev Levitsky
Lev Levitsky

Reputation: 65791

This should work:

sed 'N;s/^\([[:space:]]*\)\n\([[:space:]]*\)$/\1\2/;P;D' file

Upvotes: 0

Related Questions