batch:具有2个变量的循环子串

时间:2015-05-10 09:51:23

标签: batch-file for-loop

我有一个循环遍历文件,获取实际文件名(不包括整个路径)并尝试检查某个列表中是否存在该文件名。 我的代码是:

setlocal enabledelayedexpansion enableextensions
for /R %%j in (*.c) do (
set MYVAR=%%j
set actualFileName=%%~nj
if NOT "%MY_FILE_LIST%"=="!MY_FILE_LIST:%actualFileName%=!" set "TOCOMPILE=!TOCOMPILE! %MYVAR%"

此代码不起作用,因为使用%而不是!来访问actualFileName。 但是!MYVAR:〜!actualFileName !!也不起作用。 我该怎么办?

2 个答案:

答案 0 :(得分:1)

您可以直接使用for可替换参数修饰符来获取所需信息

for /r %%j in (*.c) do (
    echo actualFileName is %%~nj
)

其中%%~nj%%j中引用的文件的名称,没有扩展名。有关完整列表,请参阅for /?

修改以适应评论

setlocal enableextensions enabledelayedexpansion

for /r %%j in (*.c) do (
    if not "!MY_FILE_LIST:%%~nj!"=="%MY_FILE_LIST%" (
        set "TOCOMPILE=!TOCOMPILE! "%%~fj""
    )
)

这应该可以完成工作,如果没有文件名称中包含感叹号。如果无法确保这一点

setlocal enableextensions disabledelayedexpansion
for /r %%j in (*.c) do (
    setlocal enabledelayedexpansion
    if not "!MY_FILE_LIST:%%~nj!"=="%MY_FILE_LIST%" (
        for /f "delims=" %%a in ("!TOCOMPILE! ") do (
            endlocal
            set "TOCOMPILE=%%a"%%~fj""
        )
    ) else endlocal
)

答案 1 :(得分:1)

setlocal enabledelayedexpansion enableextensions
for /R %%j in (*.c) do (
 set MYVAR=%%j
 set lastIndex= some calculation to find last index of /


 for /f "tokens=* delims=" %%# in ("!lastIndex!") do (
    set actualFileName=!MYVAR:~%%#!
 )

)

使用另一个嵌套的FOR