Thoughts on life, liberty, and information technology

Using the FOR command to copy files listed in a text file

A coworker asked me for a script. Here’s the request:

… would want to copy all files on this list [an attached text document] to another location (doesn’t really matter where for now). All are currently located in \\server\share\folder. The path in the new location should begin with the part after “folder”…

In a nutshell, here is the high-level description of what the script must do:

Given a text file which provides a list of files, copy the files from a fixed source to a fixed destination, recreating the directory trees on the destination. A simple file copy won’t work because there may be files in the source folders which should not be copied.

Sample content of the text file is:

client\CD120\Samarai Legends\Drafts\drafts folder.txt
client\CD120\Samarai Legends\Inbox\Legends.doc
client\CD120\Bushido Warriors\Inbox\Warrior Code.doc

The solution to this is to make a simple batch file that parses the content of the text file, generating the appropriate xcopy command to copy the file. We’ll call the batch file xcopylist.bat; its one line of content is below. Change c:\temp\ to whatever path you want the files copied to. (I used c:\temp\ for testing.) Change \\server\share\folder to the root folder of the files to copy.

for /f "delims=" %%i in (filelist.txt) do echo D|xcopy "\\server\share\folder\%%i" "c:\temp\%%i" /i /z /y

Put the file list in the same directory as the batch file and name the file list filelist.txt. Then run the batch file and viola! You’ve got to love the for command, which lets you (among other things) parse text files and use the line-by-line output. Another trick in here is the output parser pipe, which allows us to automatically press the “D” key with each xcopy command.

Note: The batch file overwrites files in the destination automatically. To turn this off (have it prompt you), change /y to /y- in the batch file. However, if you’re using Windows NT 4.0, just delete the /y switch altogether – it’s only supported in Windows XP and Windows 2000.

146 responses to “Using the FOR command to copy files listed in a text file”

  1. Copying Folders and Files From A List in Command Prompt | Chris Tierney

    […] I had a unique request to copy a list of folders out of a greater collection of folders. Seeking the best way to do this I found this solution thanks to sidesofmarch: […]

    Like

  2. Ashik Avatar
    Ashik

    Hi Brian,
    I need to copy the content of muiltiple files in one file
    e.g file1.txt+file2.txt+file3.txt to filex.txt

    I use the copy command to do that, but the beginning content of file2 is being copy on the same end of line of file1.txt and file3 being copy the end of file2.txt
    There is an overlapping at the end of each file.
    All i need is the all the 3 files to be copied into one file named filesx.txt

    Thanking you in advance for your support

    Ashik

    Like

  3. brian Avatar
    brian

    @Ashik — sounds like you need to add a line break between files.

    Create a file, break.txt, with its only content being a blank line (i.e. open notepad, press enter, save file). Copy this file between the other file copies when appending files together and it will ensure a line break between files.

    Like

  4. Tom Avatar
    Tom

    Hi Brain,

    No sure if you can help, I’m trying to write a copy script that will search multiple directories on a network share for specific file names that are listed in a text file, then move them into a new folder, doesn’t need to keep folder structure in destination folder. I want to dump it all in one folder

    ex.

    mytextfile.txt

    abc
    abcd
    abcde
    etc.
    etc.

    Thanks For any info you cna provide

    Like

  5. Tom Avatar
    Tom

    So this is what I have, but it doesn’t seem to even search sub-directories for the files so my output is,
    The system cannot find the file specified.
    0 file(s) copied.

    I know the files are there just within sub-folders

    for /f “delims=” %%i in (filelist.txt) do (
    copy /y “F:\network_sahre\%%i*” “F:\network_share\Temp”
    )
    PAUSE

    Like

  6. brian Avatar
    brian

    @Tom, In your COPY command, try including the /s switch to also search sub-directories.

    Like

  7. Robert Avatar
    Robert

    Brian, You have got me on the right path. However, I’d like to delete the source files after they have been copied leaving the source folders intact because they have other files in them. Thanks

    Your code I used.

    for /f “delims=” %%i in (list.txt) do xcopy “C:\Users\BEAZLEYBUB\Desktop\New folder\New folder\%%i?” “C:\Users\BEAZLEYBUB\Desktop\New folder\Copied” /i /z /y /s

    Like

  8. brian Avatar
    brian

    @Robert — easiest thing is to use the ROBOCOPY command instead of XCOPY, and use the /mov (move) switch, which moves files instead of copying them.

    Like

  9. Joop Avatar
    Joop

    Hi all,

    I want to do the following thing:

    I have an output of a DIR search result on a specific term “test” on volume c: in a text file, eg

    c:\Test
    c:\Joop\Test
    c:\John\Joop\Test

    I want to use this text file to make robocopy copy these folders and content to another drive/volume.
    I want to keep the exact folder structure in the destination drive, eg f:

    f:\Test
    f:\Joop\Test
    f:\John\Joop\Test

    I tried the For \f “delims=” %%I to read the strings of the text file and use the %%I as source for robocopy, but how can i make a destination path in the same way? I cannot use %%I for that, as the driveletter (c:) is wrong in that case.

    Leave the destination empty results in

    f:\file.txt
    f:\Test
    f:\Joop

    (Without the root directories)

    Any suggestion?

    Thanx!

    (Sorry for my bad English)

    Like

  10. B.Ng Avatar
    B.Ng

    Hi Brian,

    Great work with this blog.

    I had a quick question – probably the easiest one you’ve had to deal with. I’m new to scripting and I’m attempting to copy files with the contents “Parker” from a specific to another folder. The files have different extensions and identical file-names.

    For example:
    1.000001.pdf
    1.000001.txt
    1.000001.xml
    1.000001.doc

    2.000001.pdf
    2.000001.txt
    2.000001.xml
    2.000001.doc

    When I run the below script, only one of the pdfs is copied to the folder. I want where it copies all the pdfs. I’ve checked these pdfs and they do indeed have the content “Parker.” How would you adjust this script?

    for /f “delims=” %%a in (‘findstr /m /c:”Parker” .‘) do echo F|xcopy “%%~Na.*” “C:\Test” /i /z /y

    Thanks in advance

    Like

  11. manu Avatar
    manu

    i would like to copy a folder on my c drive to a set of PC’s on the network

    PC names are in a txt file

    Please help

    Thanks

    Like

  12. killean Avatar
    killean

    does anyone know how to Create a batch file that automatically backups the users document folders. It needs to check if files exist in the destination, copy only files that have changed since the last time it was ran. It will need to create any files or folders that are new since last backup. When started it should ask the user for their full name, user name, to close all files and folders, and ask if it is ok to proceed with back up. The files should back up to the users H: drive into a folder called backup. The backup directory will then be compressed to save space. A log should be updated when ever the batch file is used, logging employee name, user name, time, and date.

    Like

  13. dwarka Avatar
    dwarka

    hi all i required a batch file which copy folder & subfolders from clinet node to server/ How batch file will take ip address of all lan pcs pls guide or give me a single example for batch file

    Like

  14. donechild Avatar
    donechild

    please can anyone help me with this batch file but its in dutch
    the idear was to make a search batch file and than at the end of the search, the batch file should prompt and ask do you wanna save the results to notepad , if yes then its will copy all the results into notepad and than it will allow you to save it where you want . but i cant figure out the code to call the notepad and the code for copying result anyhelp?

    echo off
    title zoekopalles
    color 9f
    =-=-=–=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

    :start
    cls
    echo %TIME% %Date%
    echo Halo %username%
    echo Welkome
    echo Gelieve uw voornaam in te vullen:
    echo.
    echo.
    set /p fnaam=
    echo.
    echo.
    echo Hallo leuk om jou te ontmoeten %fnaam%!
    pause>nul

    :start
    Title Het Menu
    cls
    echo %TIME% %DATE%
    echo Maak Uw Keuzen
    echo.
    echo 1- PDF Bestanden
    echo 2- Word Bestanden
    echo 3- Opnieuw Starten
    echo 4- Informatie over uw Dir
    echo 5- File Tree

    echo.
    echo.

    :start
    choice /c:12345
    cls
    IF ERRORLEVEL 5 GOTO FileTree
    IF ERRORLEVEL 4 GOTO informatieoveruwdir
    IF ERRORLEVEL 3 GOTO start
    IF ERRORLEVEL 2 GOTO WordBestanden
    IF ERRORLEVEL 1 GOTO PDFBestanden
    GOTO START

    :pdfbestanden
    dir c:*.pdf /s

    @echo off
    echo even wachten………..
    pause>nul
    dir >> myfile.text

    :wordbestanden
    dir c:*.doc /s
    dir c:*.xls /s
    echo. Laad uw resultaat naar NotePad? J/N
    set /p ask=
    if %ask% == J goto NotePad
    if %ask% == j goto NotePad
    if %ask% == N goto START
    if %ask% == n goto START
    dir %file%
    exit

    :NotePad

    pause>nul

    GOTO START
    echo.
    echo.
    :InformatieoveruwDir
    dir c:\windows
    pause>nul
    echo start
    echo.
    echo.

    :tree
    tree C:/
    ping localhost -n 5 >nul
    pause>nul
    echo start

    :search text.
    pause>nul

    :refresh
    Title …even Wachten…
    cls
    echo …even wachten…
    goto Start

    Like

  15. donechild Avatar
    donechild

    the input and the output has to come where the notepad and pause>nul

    Like

  16. Jhoy Avatar
    Jhoy

    Hi brian,

    I need help, I need to copy specific files in a zip file and zip the copied files into another zip file.

    i have multiple zip files with file name like – Axxxxmmdd.ZIP where xxxxmmdd varies depending on date. The zip contains files such as A.txt, B.txt, TD-yyyymmdd.xxxx, TH-yyyymmdd.xxxx where yyyymmdd is the date and xxxx varies depending on the number say from 0001. I need to copy TD-yyyymmdd.xxxx and TH-yyyymmdd.xxxx and zip to another zip with filename same as the TH-yyyymmdd.xxxx. After zipping the two files, I have to send it automatically to the network’s shared folder through ftp, like \192.168.1.1\folder

    I am not really familiar with batch file. Your help is highly appreciated and hope to hear from you soon 🙂

    Like

  17. Jolly Avatar
    Jolly

    Hi All,
    Could you please help me with a Script.
    My Requirement is to check all Log Files in a location and search for a Pattern in the Files.
    If that Pattern is identified then I need to Output that Pattern into another File and display that file in the Browser.
    I have already tried few examples but I am not able to retrive the Pattern into a new File !!

    my script is :

    $Path1 = “D:\ABC*.log”
    $Text = “Error
    $Path3 = “D:\ABC\t1.html”

    $Content = Get-Content $Path1

    $Content | Foreach {
    if ($_ -ilike $Text)
    {Write-Output $_}
    }| ConvertTo-HTML | Out-File $Path3

    Appreciate a Quick Response !

    Thanks.

    Like

  18. jaderaj Avatar
    jaderaj

    I need a solution to move / copy files from master parent folder to replace files in sub folders (up to 3 levels with same names.
    Eg parent folder has 100 word doc files; it has several sub folders with 5 or 6 files in each sub folder going deep to 3 levels is folder A have sub folder b b has sub folder c .
    Files in sub folder are older version of files in main folder and need to be replaced from main folder once moved all files in main folder will be moved to respective sub folder. Main folder will have no files.
    If move is not possible I want to copy to sub folders and then all files in main folder. Your help will be of immense value thank you!!

    Like

  19. Ren Avatar
    Ren

    Hello Brian,
    If i want to move/cut the files and not copy, what command should i use.
    PS. i tried, “move” but didn’t work.

    Thanks,
    Ren

    Like

  20. brian Avatar
    brian

    To move instead of copying, replace the “xcopy “\server\share\folder\%%i” “c:\temp\%%i” /i /z /y” with something like this:

    move “\server\share\folder\%%i” “c:\temp\%%i” /y

    Like

  21. George London Avatar
    George London

    Blimey Brian – Kudos for still answering queries on this 13 years later!!

    Having trouble making it work myself, but will spend another couple of hours trying to see if I can work it out myself.
    Thanks again for the starting point.

    Like

  22. Kovendhks Avatar
    Kovendhks

    Hi! am newbie, I just need batch file for doing search file in file path given in text file and copy it then paste on it destination path given in dest.txt file.
    It was look like
    source.txt:
    59 Eg003021
    59 Eg003022
    59 Eg003023
    59 Eg003024

    dest.txt:

    D:\upload\20177_July\13-07-2017

    59 was a volume no and the Eg003021 was an folder id and search FTP folder copy it to move it on dest and create which volume and paste it.
    can anyone know how to script it for this action in windows

    Like

  23. shaad Avatar
    shaad

    Hi,

    I have n number of files in a directory with a pattern like (LLF_ABC************PDV*******.txt, LLF_DEF************PDV*******.txt etc..). And each file contains data with n number of lines in basically 3 pattern (starting with EH1, EH2 and EH3). Now I have to read all the files with that pattern as specified above and split it into 3 files with the name EH1.txt containing all the lines with EH1 data, than EH2 and EH3 similarly.
    Could you please guide me on creating the same using a windows batch script.

    Like

  24. KovendhKs Avatar
    KovendhKs

    Hi brain!
    I have some problem, the problem is copying files that are listed in text file Like below:
    Listoftext.txt
    Volume 41 Eg007865
    Volume 42 Eg006545
    Volume 44 Eg005645
    These are in like some of path \server\source\ and the volumes are like folders in above mentioned path and the Eg007865 are also folder.
    I need a batch file for search the folder in text file and inside Eg007865 search Ftp folder inside file should be copied.
    It must be paste on the path \server\dest\”Name” the name is it should be get from user value in cmd.
    And put the copied file in that named folder inside create an folder like in text file.
    It shouldbe like:
    \server\dest\joky\Volume 41\the copied file
    Like this for all in text file.
    Sorry for my bad English. I need it urgently to copy some huge files. So can u please fix with this batch.
    I’m waiting for your reply….

    Like

  25. Omar Avatar
    Omar

    I’m working on Tif documents that need to be converted to pdf and then get OCR-ed. Now if some documents creates errors during that process an error log text will be created, what I need extract those files with tif format and copy them into another folder, how to do that?
    Error: The input file is corrupt or of an unknown/unsupported type
    Document: ACE16563R0000085745.TIF
    Command: Saving

    Error: Cannot open document.
    Document: ACE16563R0000085745.TIF

    Like

  26. James Pyle Avatar
    James Pyle

    This is awesome – I needed a variation.

    I have a list of files in a textfile, but they are not exact, so I need to do something like copy TEXT.

    So if my list of files has
    Apple
    Orange
    Banana

    I want to move (Rather than copy) such as Apple. Orange. Banana. to a folder.

    Any ideas?

    Like

  27. Dhwani Avatar
    Dhwani

    Hi,

    1.Read all the paths from text file; text file contains paths on each line(paths pointing to different folder location)
    2.Create backup of those files/folders in that specific path location in the parent directory

    Ex: text.txt
    c:/temp/file1
    d:/source/file2
    c:/program/windows/app/file3.ext

    result:
    c:/temp
    file1 file1yyyymmdd
    d:/source
    file2 file2yyymmdd
    c://program/windows/app
    file3.ext file3yyyymmdd.ext

    I want to create backup for those folders in the parent folder.

    Like

  28. Anoop Avatar
    Anoop

    I am looking for a script where I want to read files from LogFile and then delete all those files mentioned in LogFile from physical location and then get the log in another logfile.

    Like

  29. kiran Avatar
    kiran

    Hi I need help from yours
    My requirement is : I have folder”region” which contain sub folder like”NA”,”NZ”,”EMEA”,”INDIA” each sub folder contain files.

    here i need each file name(only file name not content),and received date, file size help me in this thanks advance………

    Like

  30. SteveX86 Avatar
    SteveX86

    Hopefully someone on here can help me ?? (( BRIAN )) ??
    Need to perform multiple copied on a PC, the source is a LTO LTFS formatted Tape.

    I found this on the looking around but I cannot find how to format the LIST.
    https://www.ibm.com/support/knowledgecenter/en/STQNYL_2.2.2/ltfs_reference_lcp_command.html

    Would like to keep the file path from the LTO when I do the copy.
    Thanks Guys

    Like

  31. Henry Avatar
    Henry

    the input file list txt file cannot be in unicode

    Like

  32. Naina Avatar
    Naina

    I have written the following command but the files are not getting copied to the required folder:
    for /f “delims=” %%i in (G:\pdf\GJ058423.docx) do echo F|xcopy “\G:\pdf\%%i” “G:\pdf\NEW\%%i” /i /z /c
    please help me with this problem..

    Like

  33. AG Avatar
    AG

    How to move selected files from different subfolder to one single folder using DOS command?
    I have so many folders which are kept in desktop, as shown
    C:\Users\272670\Desktop\dump
    inside dump folder I have folder1 folder2 etc… folders are there
    I want to move some selected files from the folder (folder1, folder2….) to Test folder (C:\Users\272670\Desktop\dump\test)
    kindly give the DOS command for the same above.

    Like

  34. Joe Avatar
    Joe

    Hello, I am trying to following batch code to copy files from source dir to destination dir from a list:

    @echo off
    for /f “delims=.*” %%i in (list.txt) do echo D|xcopy “C:\Program Files (x86)\SharedFiles\PDF\%%i” “c:\temp” /i /z /y

    But the list contains only the file name, with not extension. For example
    file1
    file2
    file3

    Is there anyway to do this copy where it still copies the file base on just the file name and ignoring the file extension.

    Thank you!

    Like

Leave a comment