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


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 off
setlocal
set string=Hello World
call blankString 20 pad
call PadString string newString 20 pad
@echo          1         2
@echo 123456789012345678901
@echo %string%#
@echo %newString%#
set string="Hello World"
set size=20
call PadString string newString %size% pad
@echo %string%#
@echo %newString%#
endlocal

displays:

         1         2
123456789012345678901
Hello World#
Hello World         #
"Hello World"#
"Hello World"       #
PadString.bat contains:
@echo off
if \{%4\}==\{\}  @echo Syntax: PadString String newString Size blankString&goto :EOF
call set %2=%%%1%% %%%4:~0,^%3%%
call set %2=%%%2:~0,^%3%%



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish