You are not logged in.

#1 01 Nov 2014 14:01

pusto
New Member
Registered: 31 Oct 2014
Posts: 3

How to copy the newest file from all subdirectories?

Can anybody help me? I have spent many hours with folowing task:
How to copy the newest file (not files) from all subdirectories to the same structure on another
drive? I am solving it by CMD commands. All my scripts have bad result.
Any help will be appreciated.
Josef

Offline

#2 01 Nov 2014 18:12

Shadow Thief
Member
Registered: 12 Jul 2012
Posts: 205

Re: How to copy the newest file from all subdirectories?

Do the subdirectories also have subdirectories of their own that you need to copy the newest file from?

Offline

#3 01 Nov 2014 19:15

pusto
New Member
Registered: 31 Oct 2014
Posts: 3

Re: How to copy the newest file from all subdirectories?

Yes, the subdirectory has the subdirecories up to three levels. Excuse my bad English. Josef

Offline

#4 02 Nov 2014 02:59

foxidrive
Member
Registered: 04 Apr 2013
Posts: 339

Re: How to copy the newest file from all subdirectories?

Do you want the newest file in every folder to be copied?

@echo off
  REM copy the latest file in each folder, to the same folder structure on another drive
  REM to crete every folder, if it contains a file or not, then remove the REM before xcopy
  REM if any names have a ! in them then they will fail
setlocal enabledelayedexpansion
set "source=\files\util"
set "sourcedrv=c:"
set "targetdrv=d:\base\folder"
  REM xcopy "%sourcedrv%%source%" "%targetdrv%%source%\" /e /t

for /d /r "%sourcedrv%%source%" %%a in (*) do (
   pushd "%%a"
      set "latest_file="
      for /f "delims=" %%A in ('dir /b /od /a-d 2^>nul') do (set "latest_file=%%A")
         if defined latest_file (
            md "%targetdrv%%%~pnxa" 2>nul
            echo copying "!latest_file!" to "%targetdrv%%%~pnxa" 
            copy /b "!latest_file!" "%targetdrv%%%~pnxa" >nul
            )
   popd
)
pause   

Last edited by foxidrive (02 Nov 2014 04:22)

Offline

#5 12 Nov 2014 14:48

pusto
New Member
Registered: 31 Oct 2014
Posts: 3

Re: How to copy the newest file from all subdirectories?

You are the genius man! That is I just needed.
I will never be able to create such a script.
Thank you very much.
I have tried the following one but it does not work.
I would like to know where I make the mistake if would be possible.

cls
set src_dir="C:\0test"
set DEST_DIR="D:\0test"

setlocal enabledelayedexpansion
pushd
cd C:\0test

for /d /r "." %%a in (*) do (
    for /f "delims=" %%i in ('dir /b /a-d /o-d "%%~a"') do (

set "newest=%%~fi"
echo "!newest!"

xcopy "!newest!" "c:\zalohy1" /O /D /Y
    )
)
popd
setlocal disabledelayedexpansion
exit /b

Offline

Board footer

Powered by