Page 1 of 1

How to replace the script name %~n0 with a string of "-" characters of length %~n0?

Posted: 2024-Jan-10, 8:03 am
by PiotrMP006
Hi

How to replace the script name %~n0 with a string of "-" characters of length %~n0?

Code: Select all

ex. %~n0 = Test.bat

How do I change "Test.bat" to the string "---------" ?

Test.bat
--------

Re: How to replace the script name %~n0 with a string of "-" characters of length %~n0?

Posted: 2024-Jan-10, 6:29 pm
by Simon Sheppard
First you can use StrLen to get the length of the string
https://ss64.com/nt/syntax-strlen.html

Then two approaches:
Write a FOR /L loop which will build up the string you desire.
https://ss64.com/nt/for_l.html
or
Create a string far longer than you are likely to need

Code: Select all

SET "mystr=-----------------------------------------------------------------------------------"
Then use substring to select the required number/length.
https://ss64.com/nt/syntax-substring.html

Re: How to replace the script name %~n0 with a string of "-" characters of length %~n0?

Posted: 2024-Jan-12, 1:42 pm
by Hackoo
Hi ;)
Note : %~n0 give you only the name without the extension Test and %~nx0 give you the name with extension Test.bat :!:

Code: Select all

@echo off
setlocal enabledelayedexpansion
:: Get script name
set "scriptName=%~nx0"
:: Calculate script name length
call :strLen scriptName scriptNameLen 
echo %scriptName% is %scriptNameLen% characters long
pause
:: Clear screen
cls
:: Display script name with underscores
echo %scriptName%
call :MakeUnderscore %scriptNameLen%
pause
exit /b
::---------------------------------------
:: Function to calculate string length
:strLen
setlocal enabledelayedexpansion
set "str=!%~1!"
set "len=0"
:strLen_Loop
if defined str (
    set "str=!str:~1!"
    set /A len+=1
    goto :strLen_Loop
)
(endlocal & set %2=%len%)
exit /b
::---------------------------------------
:: Function to display underscores
:MakeUnderscore
set "underscore="
for /l %%i in (1,1,%1) do (
    set "underscore=_!underscore!"
)
echo %underscore%
exit /b
::---------------------------------------