find path of latest file using batch command

若如初见. 提交于 2020-01-14 05:46:06

问题


I have files named file.txt in multiple subfolders in my folder. I want to get the path of the latest file.txt

FOR /r  %%i IN ('DIR file.txt /B /O:-D') DO SET a=%%i

echo Most recent subfolder: %a% 

gives latest created folder having file.txt whereas I want the folder which has latest file.txt


回答1:


@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=1,2,*" %%a in ('
        robocopy . . file.txt /l /nocopy /is /s /nc /ns /ts /ndl /njh /njs 
        ^| sort /r 2^> nul 
        ^| cmd /v /q /c "set /p .=&echo(^!.^!"
    ') do (
        echo File found           : %%c
        echo File timestamp (UTC^) : %%a %%b
        echo Folder of file       : %%~dpc
    )

This will use the robocopy command to enumerate all the file.txt files under the current active directory, without copying anything but generating a list of all matching files with a yyyy/mm/dd hh:nn:ss utc timestamp. Then the list is sorted on the timestamp in descending order and only the first line in the output readed and echoed to be processed by the for /f tokenizer and retrieve the date, time and file with full path.

If only the folder is required and the list of files is not very large, a simplified version could be

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=1,2,*" %%a in ('
        robocopy . . file.txt /l /nocopy /is /s /nc /ns /ts /ndl /njh /njs 
        ^| sort /r
    ') do set "lastFolder=%%~dpc" & goto :done
:done
    echo Last folder : %lastFolder%

Almost the same, but instead of including a filter in the list generation to only retrieve the first line (required if the list of files is very large), here the for /f will retrieve the full list but after the first element is processed we jump out of the loop to the indicated label.



来源:https://stackoverflow.com/questions/33290804/find-path-of-latest-file-using-batch-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!