我被困在为什么%~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
答案 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