Print multiple empty lines without repeating \n

If you are using bash or ksh93 or zsh then

printf '%.0s\n' {1..3}

will produce 3 newlines. The {1..3} expands to 1 2 3, and then the printf outputs these as zero width strings followed by newline.


If a POSIX solution is required, use:

loop

Beside the obvious (and ugly looking) POSIX loop:

i=0; while [ "$((i+=1))" -le 7 ]; do echo; done

POSIX (portable)

There are other (shorter, not necessarily faster) solutions:

(1) Print spaces, convert to newlines.

printf '%*s' 30 | tr ' ' '\n'

(2) Or, to get 23 lines

seq 23 | tr -dc '\n'

(3) Using awk:

seq 23 | awk '{printf "\n"}'

(4) Assuming IFS is default

printf '%.0s\n' $(seq 23)

(5) sed appends one additional newline, for 23 newlines, use 22:

printf '%0*d' 22 | sed 'y/0/\n/'

(6) Some shells auto create all the lower numbered array elements.

zsh -c 'a[33]=1; printf "%.0s\n" "${a[@]}"'

(7) Get some NUL bytes

head -c 5 /dev/zero | tr '\0' '\n'

widely known

Those are beside the more widely known (and used) solutions:

(8) Use head counting:

yes '' | head -n 23

(9) Not POSIX. For some shells (ksh, bash, zsh at least):

printf '%.0s\n' {1..23}

other languages

And, of course, using (non POSIX) higher level languages:

(10) Perl

perl -e 'print "\n" x 23'
perl -E 'say "\n" x 22'  

(11) PHP

php -r 'echo str_repeat( "\n" , 3 );'

(12) Python

python -c 'print("\n" * 3)'

$ yes "" | head -30

to get you 30 newlines.

Tags:

Shell

Newlines