How to get a variable substring in a for loop

S

ShadowTek

I know how to pull a substring out of a variable, but I don't know how
to get a substring out of a variable in a for loop.

When I try the folluwing command...

for %G in (Input_Files\*) do echo %G:~12%

....I get this:

Input_Files\New Text Document.txt:~12%

But what I am trying to get is this:

New Text Document.txt

What is wrong with this?
 
P

Pegasus \(MVP\)

ShadowTek said:
I know how to pull a substring out of a variable, but I don't know how
to get a substring out of a variable in a for loop.

When I try the folluwing command...

for %G in (Input_Files\*) do echo %G:~12%

...I get this:

Input_Files\New Text Document.txt:~12%

But what I am trying to get is this:

New Text Document.txt

What is wrong with this?

Substring manipulation works with environmental variables.
%G is not an environmental variable, hence your problem.
There two ways to resolve this issue. Either like so:
@echo off
setlocal EnableDelayedExpansion
for %%G in (InputFiles\*.*) do (
set Name=%%G
echo !Name:~12!
)

or like so:
@echo off
for %%G in (InputFiles\*.*) do call :Sub %%G
goto :eof
:Sub
set Name=%*
echo %Name:~12%
Note that your choice of coding is fragile because
you do not specify an absolute path for the InputFiles
Folder. To make the batch file robust you must
replace this by "c:\InputFiles" (for example).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top