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

Microsoft Windows
Post Reply
PiotrMP006
Posts: 19
Joined: 2021-Sep-01, 10:57 am

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

Post 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
--------
User avatar
Simon Sheppard
Posts: 191
Joined: 2021-Jul-10, 7:46 pm
Contact:

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

Post 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
Hackoo
Posts: 5
Joined: 2021-Oct-17, 6:40 pm

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

Post 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
::---------------------------------------
Post Reply