HamstersBlue
HamstersBlue

Reputation: 115

Batch get filename from path

Hi I don't have much experience in batch-programming and have a problem. I have a .bat script that reads a file with a list of paths and i want to get the filename of these paths. I use the script in cygwin. My code in the Script:

for /F %%a in (error1.txt) do (
   set value=%%a
   FOR /F %%I IN ("%value%") DO SET MYPATHFILE=%%~nxI
)

When i run the Script %value% is empty.
Value of error1.txt:

a/b/c/d/TextIWant

Upvotes: 2

Views: 213

Answers (2)

geisterfurz007
geisterfurz007

Reputation: 5874

It looks like you will need Delayed Expansion.

The current problem is, that you want to use a variable in the same set of brackets where you changed the value in (the surrounding For-Loop).

Add setlocal EnableDelayedExpansion to your code at the top and change the %value% to !value!

You can test the problem yourself with this code:

@echo off
setlocal EnableDelayedExpansion
set foo=bar
For /L %%a (1,2,1) do (
set foo=foobar
echo.old value %foo%
echo.new value !foo!
)

I hope it helped :)

Greetings

geisterfurz007

Upvotes: 4

npocmaka
npocmaka

Reputation: 57292

you need delayed expansion or you can directly use %%a:

for /F %%a in (error1.txt) do (
   FOR /F %%I IN ("%%a") DO SET MYPATHFILE=%%~nxI
)

or

setlocal enableDelayedExpansion
for /F %%a in (error1.txt) do (
   set value=%%a
   FOR /F %%I IN ("!value!") DO SET MYPATHFILE=%%~nxI
)

Upvotes: 4

Related Questions