[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: print command

Vivek Kumar <vivek@gorave.net> writes:
> Is there any other command to print any character say "*" 80 times..

The Bash-specific solution already proposed:

        for (( i=0; i<80; ++i )); do echo -n '*'; done; echo

has the advantage that, since "echo" is an internal command, the
entire loop is executed in the current shell process.  (But see

For some other possibilities that do require launching one or more
processes, these work:

        head -c80 /dev/zero | tr '\000' '*'; echo


        dc -e '80[[*]n1-d0<a]dsax[]p'

Oddly, a little benchmarking shows that these last two are twice as
fast as the Bash-specific solution above, despite the extra process

In fact, using the crude benchmark:

        time for (( j=0; j<1000; ++j )); do XXXXX; done >/dev/null

these are the elapsed real times (in seconds on my slow computer) for
various solutions proposed in this thread:

XXXXX                                                  secs/1000
--------------------------------------------------     ---------

python -c 'print "*"*80'                                35.488
for x in `seq 80`; do echo -n \*; done; echo            10.772
yes '*' | head -n 80 | tr -d '\n'; echo                  9.051
for ((i=0;i<80;i++)); do echo -n '*'; done ; echo        9.773
perl -e 'print "*"x80 ."\n"'                             6.727
head -c80 /dev/zero | tr '\000' '*'; echo                5.787
dc -e '80[[*]n1-d0<a]dsax[]p'                            5.221

The "dc" solution seems to be persistently the fastest.  It's pretty
ugly, but hidden in a shell function:

        repstring() {
                dc -e "$1[[$2]n1-d0<a]dsax"

it still looks okay and executes fast (even though the final newline
has been moved out into a separate "echo"):

repstring 80 "*"; echo                                   5.701

It just can't be used for repeating strings with unbalanced "["/"]"

Kevin <buhr@telus.net>

Reply to: