我的任务是提取存储在txt文件中的所有文件的时间戳(带有完整路径)。我使用for循环来做这件事,但我总是得到错误的日期和时间。这是我写的:
@echo off
for /f %%a in (D:\Balaji\filepath\output3.txt) do call :Sub2 %%a
goto :eof
:Sub2
echo.
if exist %1 (
echo File %1 has arrived update the DB.
FOR %%f IN (%1) DO (
SET filedatetime=%%~tf
)
echo Datetime of %1 is: %filedatetime%
)
我得到的结果是列表中第二个文件的修改日期/时间而不是第一个文件。我哪里错了?
结果:
File D:\folder\test.txt has arrived update the DB. Datetime of D:\folder\test.txt is: File D:\folder\filenames.sql has arrived update the DB. Datetime of D:\folder\filenames.sql is: 10/19/2016 03:53 PM File D:\folder\test1.txt has arrived update the DB. Datetime of D:\folder\test1.txt is: 12/22/2016 02:20 PM File D:\folder\file.csv has arrived update the DB. Datetime of D:\folder\file.csv is: 12/22/2016 04:50 PM
答案 0 :(得分:4)
"delims="
添加到for /F
,以便不拆分包含 SPACE 字符的路径。"%~1"
而不是%1
来避免像e这样的特殊字符出现问题。 G。 ^
&
(
)
。filedatetime
,或将if
查询反转为if not exist "%~1" goto :EOF
,以避免filedatetime
被更改并读入相同的括号代码块。for
循环,因为~t
等参数引用也支持%1
修饰符。所以这是固定代码:
@echo off
for /F "usebackq delims=" %%A in ("D:\Balaji\filepath\output3.txt") do call :Sub2 "%%A"
goto :EOF
:Sub2
echo/
if not exist "%~1" goto :EOF
echo File "%~1" has arrived update the DB.
echo Datetime of "%~1" is: %~t1
实际上,你甚至不需要这个子程序:
@echo off
for /F "usebackq delims=" %%A in ("D:\Balaji\filepath\output3.txt") do (
echo/
if exist "%%~A" (
echo File "%%~A" has arrived update the DB.
echo Datetime of "%%~A" is: %%~tA
)
)
答案 1 :(得分:1)
:Sub2
echo.
if NOT exist %1 GOTO :EOF
echo File %1 has arrived update the DB.
FOR %%f IN (%1) DO SET filedatetime=%%~tf
echo Datetime of %1 is: %filedatetime%
或
:Sub2
echo.
if NOT exist %1 GOTO :EOF
echo File %1 has arrived update the DB.
FOR %%f IN (%1) DO echo Datetime of %1 is: %%~tf
问题是delayedexpansion
- 很多SO项目。在遇到最外层块时,%var%
在值的块(带括号的行序列)中被替换。有办法解决 - 阅读更多有关delayed expansion