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
:(using the
l
left-padding parameter expansion flag. You could also use ther
ight padding one here).Of course, you don't have to use
printf
. You could also useprint
orecho
here which do add a\n
by default. (printf '%s\n' "$string"
can be writtenprint -r -- "$string"
orecho -E - "$string"
inzsh
, though if$string
doesn't contain backslashes and doesn't start with-
, that can be simplified toprint "$string"
/echo "$string"
).If the end-goal is to display a list of strings padded to the width of the screen, you'd do:
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 likeprintf '%s\n'
orprint -rl --
to print one element per line except in the case where no arguments are passed to it (like whenlines=()
) in which case it prints nothing instead of an empty line).