Text Processing – How to Insert a New Line After Every N Lines

text processing

How can I use text-processing tools to insert a new line after every N lines?

Example for N=2:

INPUT:

sadf
asdf
yxcv
cxv
eqrt
asdf

OUTPUT:

sadf
asdf

yxcv
cxv

eqrt
asdf

Best Answer

With awk:

awk ' {print;} NR % 2 == 0 { print ""; }' inputfile

With sed (GNU extension):

sed '0~2 a\\' inputfile

With bash:

#!/bin/bash
lines=0
while IFS= read -r line
do
    printf '%s\n' "${line}"
    ((lines++ % 2)) && echo
done < "$1"
Related Question