JSI Tip 8154. How can I pad a string variable to a specified length?

Jerold Schulman

June 14, 2004

1 Min Read
ITPro Today logo in a gray background | ITPro Today


When generating a report in a script, it is often desirable to set the 'printed' variables to a fixed length, so that they line up under the column headings.

I have scripted PadString.bat to return a fixed length variable, padding the extra characters with spaces.

The syntax for using PadString.bat is:

call PadString String newString Size blankString

where:

String      is the variable name that contains the string.newString   is a call directed environment variable that will contain the padded String.Size        is the length of newString.blankString is the variable name that contains at least %Size% spaces.

Example:

@echo offsetlocalset string=Hello Worldcall blankString 20 padcall PadString string newString 20 pad@echo          1         2@echo 123456789012345678901@echo %string%#@echo %newString%#set string="Hello World"set size=20call PadString string newString %size% pad@echo %string%#@echo %newString%#endlocaldisplays:         1         2123456789012345678901Hello World#Hello World         #"Hello World"#"Hello World"       #

PadString.bat contains:

@echo offif {%4}=={}  @echo Syntax: PadString String newString Size blankString&goto :EOFcall set %2=%%%1%% %%%4:~0,^%3%%call set %2=%%%2:~0,^%3%%



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like