How to center a text in a batch output?

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

2 Answers

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.

2

Here is a batch string that displays its parameters enclosed by asterisks :

@echo off
setlocal enabledelayedexpansion
rem Set the message to issue as second line
set "msg=* %* *"
rem Calculate the length of the string
set Length=0
for /l %%A in (1,1,1000) do if "%msg%"=="!msg:~0,%%A!" ( set /a Length=%%A goto :doit
)
:doit
rem Create a string of asterisks of same length
set header=
for /l %%i in (1,1,%Length%) do set "header=!header!*
rem Issue the message
echo %header%
echo %msg%
echo %header%

Here is what it looks like when run :

image

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like