在Windows shell中,如何回显目录中最旧文件的日期?

时间:2014-10-28 17:21:02

标签: shell batch-file recursion cmd

我在批处理文件中有以下代码(效果很好),用于递归列出每个目录的文件计数目录,但除了我已经拥有的内容之外,我还需要知道当前目录中最旧文件的日期,其中它说I_NEED_YEAR_HERE,我怎么能这样做?

@echo off

setlocal disableDelayedExpansion
if "%~1"=="" (call :recurse ".") else call :recurse %1
exit /b

:recurse
setlocal
set fileCnt=0
for /d %%D in ("%~1\*") do call :recurse "%%~fD"
for /f %%F in ('dir /b /a-d "%~1\*" 2^>nul ^| find /v /c ""') do (
  set /a fileCnt+=%%F 
)
echo %~f1 has %fileCnt% files and the oldest file is from year I_NEED_YEAR_HERE
( 
  endlocal
  set /a fileCnt+=%fileCnt%
)

exit /b

2 个答案:

答案 0 :(得分:0)

使用您的代码,您必须添加新的FOR循环并启用Delayedexpansion

这样的事情会起作用:

@echo off
setlocal enableDelayedExpansion
if "%~1"=="" (call :recurse ".") else call :recurse %1
exit /b

:recurse
setlocal
set fileCnt=0
for /d %%D in ("%~1\*") do call :recurse "%%~fD"
for /f %%F in ('dir /b /a-d "%~1\*" 2^>nul ^| find /v /c ""') do (
  set /a fileCnt+=%%F
)    
pushd  "%~f1" 2>nul
set "$date="
for /f "delims=" %%x in ('dir /b/o-d') do (set $date=%%~tx
set $date=!$date:~6,4!)
popd
echo %~f1 has %fileCnt% files and the oldest file is from year !$date!
( 
 endlocal 
  set /a fileCnt+=%fileCnt%
)

exit /b

你可以使用2 FOR循环,这更紧凑,更容易:

@echo off
setlocal enableDelayedExpansion
for /f "delims=" %%a in ('dir /b/ad/s "%1"') do (
pushd "%%a"
set $c=0
for /f %%x in ('dir /b/o-d/a-d') do (
set "$date=%%~tx"
set "$date=!$date:~6,4!"
set /a $c+=1)
popd
if !$c!==0 set $date=[Null]
echo %%a has !$c! files and the oldest file is from year !$date!
)

答案 1 :(得分:0)

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
PUSHD "%sourcedir%"


setlocal DISABLEDELAYEDEXPANSION
SET /a grand=0
if "%~1"=="" (call :recurse ".") else call :recurse %1
ECHO Total=%grand%

POPD
GOTO :eof

:recurse
setlocal
for /d %%D in ("%~1\*") do call :recurse "%%~fD"
set /a fileCnt=0
SET "oldest="
for /f "delims=" %%F in ('dir /b /a-d /o-d "%~1\*" 2^>nul') do (
  set /a fileCnt+=1
  IF NOT DEFINED oldest FOR %%O IN ("%~1\%%~nxF") DO SET "oldest=%%~tO %~1\%%~nxF"
)
echo %~f1 has %fileCnt% files and the oldest file is from year %oldest:~6,4% %oldest%
(
 ENDLOCAL
 SET /a grand=%grand%+%fileCnt%
)

exit /b

GOTO :EOF

稍微重新格式化以适合我在测试目录u:\ sourcedir上的测试。

我将oldest设置为日期和文件名。选择所需的数据是一个适当的子串的问题,它需要在#files<>上进行门控。 0

有趣的是,SET /a grand=%grand%+%fileCnt%工作而SET /a grand+=%fileCnt%失败了......