Orr22
Orr22

Reputation: 161

How to add N blank lines between all rows of a text file?

I have a file that looks

a
b
c
d

Suppose I want to add N lines (in the example 3, but I actually need 20 or 100 depending on the file)

a


b


c


d 

I can add one blank line between all of them with sed

sed -i '0~1 a\\' file

But sed -i '0~3 a\\' file inserts one line every 3 rows.

Upvotes: 5

Views: 1643

Answers (5)

AI Chung
AI Chung

Reputation: 61

  • To add 1 blank line after each line, use the following command line (basically, $ matches end of the line):

    sed -e 's/$/\n/' file
    
  • To add 3 blank lines after each line, use the following command line:

    sed -e 's/$/\n\n\n/' file
    

Upvotes: 2

potong
potong

Reputation: 58518

This might work for you (GNU sed):

sed ':a;G;s/\n/&/2;Ta' file

This will add 2 blank lines following each line.

Change 2 to what ever number you desire between each line.

An alternative (more efficient?):

sed '1{x;:a;/^.\{2\}/!s/^/\n/;ta;s/.//;x};G' file

Upvotes: 1

Thor
Thor

Reputation: 47189

With sed and corutils:

N=4
sed "\$b;$(yes G\; | head -n$N)" infile

Similar trick with awk:

N=4
awk 1 RS="$(yes \\n | head -n$N | tr -d '\n')" infile

Upvotes: 1

Cyrus
Cyrus

Reputation: 88839

With GNU awk:

awk -i inplace -v lines=3 '{print; for(i=0;i<lines;i++) print ""}' file

Update with Ed's hints (see comments):

awk -i inplace -v lines=3 '{print; for(i=1;i<=lines;i++) print ""}' file

Update (without trailing empty lines):

awk -i inplace -v lines=3 'NR==1; NR>1{for(i=1;i<=lines;i++) print ""; print}' file

Output to file:

a



b



c



d

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627327

You may use with GNU sed:

sed -i 'G;G;G' file

The G;G;G will append three empty lines below each non-final line.

Or, awk:

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

See an online sed and awk demo.

If you need to set the number of newlines dynamically use

nl="
"
awk -v nl="$nl" 'BEGIN{for(c=0;c<3;c++) v=v""nl;ORS=v};1' file > newfile

Upvotes: 6

Related Questions