Reputation: 351
echo off
set "MasterFolder=C:\Users\Development\test_folder"
SetLocal EnableDelayedexpansion
@FOR /f "delims=" %%f IN ('dir /b /s "%MasterFolder%\*.txt"') DO (
set /a "idx+=1"
set "FileName[!idx!]=%%~nxf"
set "FilePath[!idx!]=%%~dpFf"
)
for /L %%i in (1,1,%idx%) do (
echo [%%i] "!FileName[%%i]!"
set "loc=%MasterFolder%\!FileName[%%i]!"
echo path: %MasterFolder%\!FileName[%%i]!
echo loc: !loc!
FOR /F "tokens=1,2 delims=:" %%1 in ('findstr /o "^" "%MasterFolder%\test_1.txt"') DO (
set new_pos=%%1
echo new_pos !new_pos!
)
)
The above code works, However, the following codes do not work.
echo off
...
FOR /F "tokens=1,2 delims=:" %%1 in ('findstr /o "^" "%MasterFolder%\!FileName[%%i]!"') DO (
set new_pos=%%1
echo new_pos !new_pos!
)
)
echo off
...
FOR /F "tokens=1,2 delims=:" %%1 in ('findstr /o "^" "!loc!"') DO (
set new_pos=%%1
echo new_pos !new_pos!
)
)
All I did was replacing test_1.txt to !FileName[%%i]!, or use a new variable and replace all as "!loc!".
But the last two codes do not work, and I need this manner, since it get file names in the folder automatically by the first for loop.
I guess there is an error either in findstr, or variable expansion order, but it is hard for me to figure it out.
Upvotes: 2
Views: 782
Reputation: 82297
It's obvious!
When using !file...
, you introduce an exclamation mark into the line.
This triggers phase 5 (delayed epxansion phase) of the parser.
In that phase the variables are expanded and carets are used to escape the next character, independent where they are (quoted or not)!
Therefore you your search string "^"
is trasformed to ""
.
Simply double the caret to findstr /o "^^" !File...
setlocal EnableDelayedExpansion
echo One Caret "^"
echo One Caret "^" and a bang ^^!
Output
One Caret "^"
One Caret "" and a bang !
Upvotes: 2