Tuesday, December 19, 2017

windows - Batch find and copy files from a file list



I have a drive with several thousands of pictures on it. I've copied it all to another drive in which I've been organizing them slowly over several months. I've discovered a ton of corrupted files but found that the on the original drive, they aren't corrupted.



What I'd like to do is have a batch file that will read filenames from a text file and search the original drive for the filename, then copy it to a specified folder.



Since the original drive is unsorted, there could be duplicates so I'd like to copy all of the copies of that filename to the new folder. I have a script that might do it (see below) but it doesn't seem to be working because of the long filenames. For example, "2008-06-27 02.06.37.jpg" ... the script will search for "2008-06-27" instead of the full filename.



Any thoughts on how to fix this?




Here is my work that I have so far that's still not working as expected:



@ECHO OFF

SETLOCAL ENABLEDELAYEDEXPANSION

cls

set dest=F:\ERRORS\recovered


for /f %%f in (F:\ERRORS\errorlist.txt) do (

set i=1

for /f "tokens=*" %%F IN ('dir /S /B /A:-D "%%f"') Do (

for %%N in ("%%F") Do (

set name=%%~NN


set ext=%%~XN

)

copy "%%F" "%dest%\!name!_!i!!ext!"

set /A i=!i!+1

)


)

ENDLOCAL

Answer



You should add the "TOKENS=*" to the FOR /F loop that reads from the file list to ensure that lines read from within the file list which have spaces between literal characters are not interpreted as a delimiter or new line thus cutting off the character string iterated at the space and not getting the whole line of characters you need it to loop through including any spaces before carriage return or line feeds.



@ECHO OFF


SETLOCAL ENABLEDELAYEDEXPANSION
cls

set dest=F:\ERRORS\recovered
for /f "TOKENS=*" %%f in (F:\ERRORS\errorlist.txt) do (
set i=1
for /f "tokens=*" %%F IN ('dir /S /B /A:-D "%%~f"') Do (
for %%N in ("%%F") Do (
set name=%%~NN
set ext=%%~XN

)
copy "%%~F" "%dest%\!name!_!i!!ext!"
set /A i=!i!+1
)
)
ENDLOCAL






Further Resources




  • FOR /?




       tokens=x,y,m-n  - specifies which tokens from each line are to
    be passed to the for body for each iteration.
    This will cause additional variable names to
    be allocated. The m-n form is a range,

    specifying the mth through the nth tokens. If
    the last character in the tokens= string is an
    asterisk, then an additional variable is
    allocated and receives the remaining text on
    the line after the last token parsed.



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...