sed and printf – Repeating a Character and Appending Newline

printfsed

In order to repeat a character N times, we could use printf. E.g to repeat @ 20 times, we could use something like this:

N=20
printf '@%.0s' $(seq 1 $N)

output:

@@@@@@@@@@@@@@@@@@@@

However, there is no newline character at the end of that string. I've tried piping the output to sed:

printf '@%.0s' $(seq 1 $N) | sed '$s/$/\n/'

Is it possible to achieve the same result with a single printf (adding a newline character at the end of the output) without using sed?

Best Answer

With zsh:

printf '%s\n' ${(l[20][@])}

(using the l left-padding parameter expansion flag. You could also use the right padding one here).

Of course, you don't have to use printf. You could also use print or echo here which do add a \n by default. (printf '%s\n' "$string" can be written print -r -- "$string" or echo -E - "$string" in zsh, though if $string doesn't contain backslashes and doesn't start with -, that can be simplified to print "$string"/echo "$string").

If the end-goal is to display a list of strings padded to the width of the screen, you'd do:

$ lines=(short 'longer text' 'even longer')
$ print -rC1 -- ${(ml[$COLUMNS][@][ ])lines}
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ short
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ longer text
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ even longer
$ print -rC1 -- ${(mr[$COLUMNS][@][ ])lines}
short @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
longer text @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
even longer @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Where the m flag causes zsh to take into account the display width of each character (like for those double-width characters above (which your browser may not render with exactly double-width, but your terminal should)).

print -rC1 -- is like printf '%s\n' or print -rl -- to print one element per line except in the case where no arguments are passed to it (like when lines=()) in which case it prints nothing instead of an empty line).

Related Question