Remove first and last character from a String in a Windows Batch file

Metalhead89 picture Metalhead89 · Aug 22, 2012 · Viewed 49.3k times · Source

I have the following string inside my Windows batch file:

"-String"

The string also contains the twoe quotation marks at the beginning and at the end of the string, so as it is written above.

I want to strip the first and last characters so that I get the following string:

-String

I tried this:

set currentParameter="-String"
echo %currentParameter:~1,-1%

This prints out the string as it should be:

-String

But when I try to store the edited string like this, it fails:

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%

Nothing gets printed out. What do I do wrong?


This really is strange. When I remove the characters like this it works:

set currentParameter="-String"
set currentParameter=%currentParameter:~1,-1%
echo %currentParameter%

it prints out:

-String

But actually my batch is a bit more complicated and there it does not work. I will show what I programmed:

@echo off

set string="-String","-String2"

Set count=0
For %%j in (%string%) Do Set /A count+=1


FOR /L %%H IN (1,1,%COUNT%) DO ( 

    echo .
        call :myFunc %%H
)
exit /b

:myFunc
FOR /F "tokens=%1 delims=," %%I IN ("%string%") Do (

    echo String WITHOUT stripping characters: %%I 
    set currentParameter=%%I
    set currentParameter=%currentParameter:~1,-1%

    echo String WITH stripping characters: %currentParameter% 

    echo .

)
exit /b   

:end

And the output is:

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters:
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: ~1,-1
.

But what i want is:

.
String WITHOUT stripping characters: "-String"
String WITH stripping characters: -String
.
.
String WITHOUT stripping characters: "-String2"
String WITH stripping characters: -String2
.

Answer

phani picture phani · Mar 7, 2014

hope will help you. echo String WITHOUT stripping characters: %%I

set currentParameter=%%I
set currentParameter=!currentParameter:~1,-1!

echo String WITH stripping characters: !currentParameter! 

echo .

It might work. Try this once.