How to center a text in a batch output

batchbatch filecommand line

I'm implementing a batch program that execute some different things in different steps.
For each step, I want to display a "friendly" text header like this:

*************************************************************
*                      MY FIRST STEP                        *
*************************************************************

"MY FIRST STEP" is a variable that could have a various length.

My question: do you have an algorithm or a function that could return this string as output with the string header to display in input parameter ?

Thanks in advance.

Regards

Best Answer

The width of all the symbols depends heavily on the font used. There is no easy way to measure pixel width of a string, but sometimes you don't need it.

Windows command line by default uses Lucida Console, a monospace font, which makes things easy. Example would be:

@echo off
setLocal EnableDelayedExpansion
set "STR=Boom^!"
set "SIZE=50"

set "LEN=0"
:strLen_Loop
   if not "!!STR:~%LEN%!!"=="" set /A "LEN+=1" & goto :strLen_Loop

set "stars=****************************************************************************************************"
set "spaces=                                                                                                    "

call echo %%stars:~0,%SIZE%%%
set /a "pref_len=%SIZE%-%LEN%-2"
set /a "pref_len/=2"
set /a "suf_len=%SIZE%-%LEN%-2-%pref_len%"
call echo *%%spaces:~0,%pref_len%%%%%STR%%%%spaces:~0,%suf_len%%%*
call echo %%stars:~0,%SIZE%%%

endLocal

SIZE here is the length of the block you want to output, make sure it's big enough to fit all the possible lines inside it.

I'll remind, that this will output a pretty block in monospace fonts only.

EDIT: Fixed the LEN initialization.

Related Question