为什么我的批处理找不到列出子文件夹文件的路径?

时间:2015-09-17 15:35:28

标签: batch-file

我被困在为什么%~dp0加上%%我似乎没有在嵌套中工作...

REM for each folder
for /f "tokens=*" %%I in ('dir /ad /b "%~dp0\*.*"') do (
ECHO. >> "%~dp0\_list of files with extension_.txt"
ECHO. -------- %%I  -------- >> "%~dp0\_list of files with extension_.txt"
ECHO. >> "%~dp0\_list of files with extension_.txt"

REM for each file in that folder
REM in line below, the path of %~dp0 plus %%I does not seem to get used???
for /R "%~dp0%%I" %%f in (*.*) do (
echo %%~nf%%~xf >> "%~dp0\_list of files with extension_.txt"
)

ECHO. >> "%~dp0\_list of files with extension_.txt"
)

如果我在第二个之前做了ECHO%~dp0或者ECHO %%我看起来不错,但看起来For不走这条路,知道为什么?

我今天得到的输出是......

------ Folder1 name ------

------ Folder2 name ------

我想要的输出是这样的......

------ Folder1 name ------
file1.txt
file2.txt
file3.txt

------ Folder2 name ------
file1.txt
file2.txt

2 个答案:

答案 0 :(得分:2)

您不能在for /f命令的“options”部分或for /r的起始路径中使用延迟扩展或delayedexpansion可替换参数。在for@echo off setlocal enableextensions disabledelayedexpansion ( for /d %%D in ("%~dp0\*") do ( pushd "%%~fD" echo( -------- %%~nxD -------- for /r %%F in (*) do echo(%%~nxF echo( popd ) ) >> "%~dp0\_list of files with extension_.txt" 参数扩展发生之前解析这些元素。

但你可以解决它改变当前活动文件夹并从那里迭代

name,score,date
Bob,93,2014
Bob,85,2015
Barry,70,2015
...

答案 1 :(得分:1)

以下FOR command语法模式中IN关键字之前的所有部分(换句话说,所有大写字母)仅解析一次,甚至在解析时评估

FOR /R [[DRIVE:]PATH] %%PARAMETER IN (set) DO command                     
FOR /F ["OPTIONS"]    %%PARAMETER IN (filenameset) DO command             
FOR /F ["OPTIONS"]    %%PARAMETER IN ("text string to process") DO command
FOR /F ["OPTIONS"]    %%PARAMETER IN ('command to process') DO command    

在您的情况下,解析外部循环for /R "%~dp0%%I" %%f in (*.*) do (时会解析内部for /f "tokens=*" %%I in ... do (命令。
例如,如果您的脚本保存为for /R "d:\bat\SO\%I" %f in (*.*) do (,则会将其解析为并执行 D:\bat\SO\32634468.bat

假设您在名为somefile.txt的文件夹中有%I,那么您的脚本(因输出确定性和准确性而更改为echo %%~dpnxf而不是echo %%~nf%%~xf)应输出类似

------ %I ------
d:\bat\SO\%I\somefile.txt

------ Folder1 name ------
d:\bat\SO\%I\somefile.txt

------ Folder2 name ------
d:\bat\SO\%I\somefile.txt

解决方案#1 :使用(功能相当)

for /F "delims=" %%f in ('dir /B /S /A-D "%~dp0%%I\*.txt" 2^>NUL') do (

解决方案#2 call a subroutine

@ECHO OFF
SETLOCAL EnableExtensions

REM for each folder
for /f "tokens=*" %%I in ('dir /ad /b "%~dp0\*.*"') do (
  ECHO. >> "%~dp0\_list of files with extension_.txt"
  ECHO. -------- %%I  -------- >> "%~dp0\_list of files with extension_.txt"
  ECHO. >> "%~dp0\_list of files with extension_.txt"

  REM for each file in that folder
  set "_fldr=%%I"
  CALL :fldr "%~dp0\_list of files with extension_.txt"

  ECHO. >> "%~dp0\_list of files with extension_.txt"
)


rem next GOTO :EOF command to skip the :fldr label 
GOTO :EOF
:fldr
REM in line below, the path of %~dp0 plus %_fldr% seems to get used
for /R "%~dp0%_fldr%" %%f in (*.txt) do (
  echo %%~nf%%~xf >>"%~1" 
)
GOTO :EOF
rem previous GOTO :EOF command to return from the :fldr subroutine