How to center align text.

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
fugitive
Posts: 19
Joined: 09 Mar 2017 02:26

How to center align text.

#1 Post by fugitive » 09 Mar 2017 02:46

Hello everyone,I'm looking forward to your help
There is a txtfile:

Code: Select all

When Day Is Done

If the day is done ,

If birds sing no more .

If the wind has fiagged tired ,

Then draw the veil of darkness thick upon me ,

Even as thou hast wrapt the earth with The coverlet of sleep and tenderly closed ,

The petals of the drooping lotus at dusk.

From the traverer,

Whose sack of provisions is empty before the voyage is ended ,

Whose garment is torn and dust-laden ,

Whose strength is exhausted,remove shame and poverty ,

And renew his life like a flower under

The cover of thy kindly night .

——————————now,I want it to be this way in the cmd (align center ?)

Code: Select all

                                When Day Is Done                               
                              If the day is done ,                             
                            If birds sing no more .                           
                        If the wind has fiagged tired ,                       
                 Then draw the veil of darkness thick upon me ,               
Even as thou hast wrapt the earth with The coverlet of sleep and tenderly close
                   The petals of the drooping lotus at dusk.                   
                               From the traverer,                             
         Whose sack of provisions is empty before the voyage is ended ,       
                     Whose garment is torn and dust-laden ,                   
             Whose strength is exhausted,remove shame and poverty ,           
                     And renew his life like a flower under                   
                        The cover of thy kindly night .                       


Squashman
Expert
Posts: 4150
Joined: 23 Dec 2011 13:59

Re: How to center align text.

#2 Post by Squashman » 09 Mar 2017 10:44

We actually have someone working on a macro to do just that. I am sure he will respond to your question.
viewtopic.php?f=3&t=7742

aGerman
Expert
Posts: 3869
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How to center align text.

#3 Post by aGerman » 09 Mar 2017 16:59

Try this snippet. Just change the file name at the beginning.

Code: Select all

@echo off &setlocal

set "file=poem.txt"

setlocal EnableDelayedExpansion
set "spcs=                                                  " &set "n=" &set "indent=!spcs!"
for /f "skip=4 tokens=2" %%i in ('mode con') do if not defined n set /a "cols=%%i, n=%%i/100"
for /l %%i in (1 1 %n%) do set "indent=!indent!!spcs!"

<"!file!" (
  for /f %%i in ('type "!file!"^|find /c /v ""') do for /l %%j in (1 1 %%i) do (
    set "line=" &set /p "line="
    if defined line (
      set "str=A!line!" &set "len=0"
      for /l %%k in (12,-1,0) do (
        set /a "len|=1<<%%k"
        for %%l in (!len!) do if "!str:~%%l,1!"=="" set /a "len&=~1<<%%k"
      )
      set /a "n=(cols-len)/2"
      if !n! lss 0 (
        set /a "n*=-1, len-=len-cols"
        for /f "tokens=1,2" %%k in ("!n! !len!") do echo(!line:~%%k,%%l!
      ) else for %%k in (!n!) do echo(!indent:~0,%%k!!line!
    )
  )
)

pause

Steffen

Sounak@9434
Posts: 100
Joined: 16 Dec 2016 22:31

Re: How to center align text.

#4 Post by Sounak@9434 » 09 Mar 2017 19:59

Or you can use my align.bat utility.
Align.zip
Alignment Utility
(2.02 KiB) Downloaded 153 times

A well explained and commented code, a test file and a documentation is provided.
In your case use this code.

Code: Select all

::Replace filename.txt with the file you want
for /f "tokens=*" %%a in (filename.txt) do call align.bat /m "%%a"


Or, Just in case here is a center align macro specifically made for your problem.

Code: Select all

@echo off
setlocal disabledelayedexpansion
set ^"LF=^
%= This creates a variable containing a single linefeed (0x0A) character =%
^"
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
set @align=for %%. in (1 2) do if %%.==2 (%\n%
   for /f "skip=4 tokens=2 delims= " %%a in ('mode con') do if not defined _line set "_line=%%a"%\n%
   for /f "tokens=*" %%b in (!argv!) do (%\n%
      set "_text=%%b"%\n%
      set "_len=0"%\n%
      set "s=A!_text!"%\n%
      for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (%\n%
         if "!s:~%%P,1!" neq "" (%\n%
            set /a "_len+=%%P"%\n%
            set "s=!s:~%%P!"%\n%
         )%\n%
      )%\n%
      set /a _space=_line-_len%\n%
      set /a _space/=2%\n%
      set "_bsp="%\n%
      for /l %%c in (1,1,!_space!) do set "_bsp=!_bsp! "%\n%
      echo(!_bsp!!_text!%\n%
   )%\n%
) ELSE setlocal enabledelayedexpansion^&setlocal^&set argv=
::Replace filename.txt with your file
%@align% filename.txt


Sounak

fugitive
Posts: 19
Joined: 09 Mar 2017 02:26

Re: How to center align text.

#5 Post by fugitive » 10 Mar 2017 02:41

I would like to sincerely say thank you to each of you,but I'm a stranger to this forum,not so clear about its function...So,I express my gratitude on this floor.THANKS!!

fugitive
Posts: 19
Joined: 09 Mar 2017 02:26

Re: How to center align text.

#6 Post by fugitive » 10 Mar 2017 03:00

And,I wrote a batch script last night also.
it may be not so appropriate, but I would like to share with you:

Code: Select all

@echo off
setlocal enabledelayedexpansion
set "space=    "
for /f "delims=" %%a in (poem.txt) do (
   setlocal
   for %%b in (%%a) do set /a n+=1
   set /a num=80-n*5
   set /a num=num/2/5
   for /l %%c in (1,1,!num!) do set/p=%space%<nul
   set/p=%%a<nul
   echo;
   endlocal
)
pause

rem I assume that each word takes up 5 spaces

einstein1969
Expert
Posts: 774
Joined: 15 Jun 2012 13:16
Location: Italy, Rome

Re: How to center align text.

#7 Post by einstein1969 » 10 Mar 2017 11:07

Hi,

you can center a string at specified length using this tip:

Code: Select all

@echo off & setlocal EnableDelayedExpansion

:: size of box or windows (specified length)
set sizemax=70

set s=blablablablablabla

for /L %%# in (1,2,!sizemax!) do if "!s:~%sizemax%,1!" == "" set "s= !s! "

set s=!s:~1,%sizemax%!& echo(^|!s!^|


with this tip you can bypass use of strlen


einstein1969

Jer
Posts: 160
Joined: 23 Nov 2014 17:13
Location: California USA

Re: How to center align text.

#8 Post by Jer » 10 Mar 2017 13:03

Center aligning to a fixed length is good to know.
Here is an adaptation of that combined with other
methods I have learned from this forum's participants.
Post your comments if you find any part of this code
needs correction or could be improved in some way.

Code: Select all

@echo off
setlocal & setlocal
set "sourcefile=myfile.txt"
> "%sourcefile%" ( echo( & echo A picture is worth 1,000 words.
echo(
echo I
echo hope
echo this may be useful
echo to someone.
echo(
echo Never stop learning!
echo( ) & endlocal & set "sourcefile=%sourcefile%"

setlocal EnableDelayedExpansion

rem specified string length
Set "strFixedLen=40"
Set "indent=4"
Set "lBdr=^|" & Set "rBdr=!lBdr!"
Set "hz=+"

If %indent% gtr 0 (
  For /L %%n In (1,1,%indent%) Do (
    Set "lBdr= !lBdr!"
    Set "hz= !hz!"
))

For /L %%n In (1,1,%strFixedLen%) Do Set "hz=!hz!-"
Set "hz=%hz%+" & Echo !hz!

For /F %%j In ('Type %sourcefile%^|Find "" /v /c') Do Set /A "linecount=%%j"
Set /A "x=%linecount%-1"

< "%sourcefile%" (For /L %%i In (0,1,%x%) Do (
   Set "s="
   Set /P "s="
   If "0!s!" equ "0" Set "s= "
   For /L %%# In (1,2,!strFixedLen!) Do If "!s:~%strFixedLen%,1!" == "" Set "s= !s! "
   Set s=!s:~1,%strFixedLen%!& Echo(%lBdr%!s!%rBdr%
))

Echo %hz%
endlocal & endlocal & exit /b


edited: 2nd layer of setlocal needed to keep sourcefile var out of the environment
edited code 3/11/17 - add indent, lBdr and rBdr vars., change "sizemax" to "strFixedLen"
Last edited by Jer on 11 Mar 2017 10:31, edited 2 times in total.

Thor
Posts: 43
Joined: 31 Mar 2016 15:02

Re: How to center align text.

#9 Post by Thor » 10 Mar 2017 15:55

Jer wrote:Center aligning to a fixed length is good to know.
Here is an adaptation of that combined with other
methods I have learned from this forum's participants.
Post your comments if you find any part of this code
needs correction or could be improved in some way.

Code: Select all

@echo off
setlocal
set "sourcefile=myfile.txt"
> "%sourcefile%" ( echo( & echo A picture is worth 1,000 words.
echo(
echo I
echo hope
echo this may be useful
echo to someone.
echo(
echo Never stop learning!
echo( ) & endlocal & set "sourcefile=%sourcefile%"

setlocal EnableDelayedExpansion

rem size of box or windows (specified length)
set sizemax=40

Set "hz=+" & For /L %%n In (1,1,%sizemax%) Do Set "hz=-!hz!"
Set "hz=+%hz%" & Echo !hz!
For /F %%j In ('Type %sourcefile%^|Find "" /v /c') Do Set /A "linecount=%%j"
Set /A "x=%linecount%-1"

< "%sourcefile%" (For /L %%i In (0,1,%x%) Do (
   Set "s="
   Set /P "s="
   If "0!s!" equ "0" Set "s= "
   For /L %%# In (1,2,!sizemax!) Do If "!s:~%sizemax%,1!" == "" Set "s= !s! "
   Set s=!s:~1,%sizemax%!& Echo(^|!s!^|
))

Echo %hz%
endlocal & exit /b


I think your "sizemax" value in your script need to take care of the fact you add the border characters.
So the actual value will be sizemax = sizemax - 2.

Let's say I have a command prompt window with the screensize set to 90. If I specify 90 as the sizemax then the border charactesr will not fit to it for right now.

Jer
Posts: 160
Joined: 23 Nov 2014 17:13
Location: California USA

Re: How to center align text.

#10 Post by Jer » 10 Mar 2017 17:19

My thoughts are that when the sizemax value is manually set,
the coder has taken into account that the console window width
and the size of the font will display the text correctly inside
whatever border thickness the box verticals happen to be.

Box verticals may be doubled or more by the batch coder.
The coder has to test that the finished product will fit the
window that will display it.
:)

Thor
Posts: 43
Joined: 31 Mar 2016 15:02

Re: How to center align text.

#11 Post by Thor » 10 Mar 2017 18:04

Ok then I misinterprete the "sizemax" meaning with "max screensize" window meaning. :mrgreen:

Jer
Posts: 160
Joined: 23 Nov 2014 17:13
Location: California USA

Re: How to center align text.

#12 Post by Jer » 11 Mar 2017 10:40

The variable name sizemax would not have been my choice because
it does not specify what is being sized in the original script.

I edited the batch code in my post above and renamed sizemax to strFixedLen, and
also added the functionality of indentation.
Jerry

Sounak@9434
Posts: 100
Joined: 16 Dec 2016 22:31

Re: How to center align text.

#13 Post by Sounak@9434 » 11 Mar 2017 11:14

einstein1969 wrote:Hi,

you can center a string at specified length using this tip:

Code: Select all

@echo off & setlocal EnableDelayedExpansion

:: size of box or windows (specified length)
set sizemax=70

set s=blablablablablabla

for /L %%# in (1,2,!sizemax!) do if "!s:~%sizemax%,1!" == "" set "s= !s! "

set s=!s:~1,%sizemax%!& echo(^|!s!^|


with this tip you can bypass use of strlen


einstein1969


Brilliant method einstein1969. Maybe the fastest among all.
I'm definitely going to update my align.bat.
Thanks. :D

Aacini
Expert
Posts: 1631
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: How to center align text.

#14 Post by Aacini » 12 Mar 2017 00:45

I devised a method to directly calculate the margin needed to center a string in a single SET /A command using an interesting trick: when a character enclosed in quotes is placed before a digit, both characters are joined to form a variable that result in a zero value if the variable is not defined. If the character is a space or not exists, the number after it is processed. For example:

Code: Select all

set /A var=10000+"thisNot"2000+" "300+"x"40+""5
10305

This trick allows to conditionally process a series of numbers in a single long expression depending on a series of characters, so all of them are processed at same time. This is the code of a solution for this problem based on this trick:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "file=poem.txt"

for /F "skip=4 tokens=2" %%a in ('mode con') do set /A "cols=%%a-1" & goto continue
:continue
set "spaces="
for /L %%i in (0,2,%cols%) do set "spaces=!spaces! "
set "formula="^^^!str:~0,1^^^!"1"
for /L %%i in (2,2,%cols%) do set "formula=!formula!+"^^^!str:~%%i,1^^^!"1"

for /F "delims=" %%a in (poem.txt) do (
   set "str=%%a"
   set "str=!str: =x!"
   set "str=!str:,=x!"
   set /A "indent=%formula%"
   for /F %%n in ("!indent!") do set "str=!spaces:~0,%%n!%%a"
   echo !str:~0,%cols%!
)

Output:

Code: Select all

                                When Day Is Done
                              If the day is done ,
                            If birds sing no more .
                        If the wind has fiagged tired ,
                 Then draw the veil of darkness thick upon me ,
Even as thou hast wrapt the earth with The coverlet of sleep and tenderly close
                   The petals of the drooping lotus at dusk.
                               From the traverer,
         Whose sack of provisions is empty before the voyage is ended ,
                    Whose garment is torn and dust-laden ,
             Whose strength is exhausted,remove shame and poverty ,
                     And renew his life like a flower under
                        The cover of thy kindly night .

Of course, if a character is a digit or an operator the SET /A command process it, so such characters (and also others that may cause errors in the arithmetic expression) must be replaced before use this method.

Antonio

ShadowThief
Expert
Posts: 950
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: How to center align text.

#15 Post by ShadowThief » 12 Mar 2017 00:50

And just for the sake of completion, here's one that I wrote a while ago that uses a temporary file.

Code: Select all

@echo off
setlocal enabledelayedexpansion
cls
set window_width=80
set "text=The quick brown fox jumps over the lazy dog."
if not "%~1"=="" set text=%~1

call :center "The quick brown fox jumps over the lazy dog."
exit /b

:center
:: Subtract the width of the window from the length of the string and divide by
:: two. Then add that many spaces to the beginning of the string.
set text=%~1
echo !text!>tmp
for %%A in (tmp) do set /a length=%%~zA-2
del tmp
set /a spaces=(%window_width%-!length!)/2

for /l %%A in (1,1,!spaces!) do (
   set "text= !text!"
)

echo !text!

Post Reply