Search code examples
batch-filedos

How can I copy a particular file from a source directory to a destination directory while recreating the folder structure


I have to use batch only . The destination folder should have the copied file along with the directory structure of the source directory (for the file copied only). Example :

Source: C:\folder1\folder2\folder3\text1.txt Destination: C:\backup

After the command is executed The destination folder should look like : C:\backup\folder1\folder2\folder3\text1.txt

I must use the command from C:\ (root directory) only . In my source there are multiple files with name ="text1.text" ,but with different folder structure. I want only that "text1.txt" to be copied whose path i am providing (source), and not all files named "text1.txt" [this can be achieved using--- xcopy Source\text1.txt* Destination /S /Y].PLease help.


Solution

  • @ECHO OFF
    SETLOCAL
    :: This command alone will accomplish the task using ONLY XCOPY
    :: BUT I'm changing the directorynames to suit my system
    ::
    XCOPY c:\sourcedir\a\b\text1.txt u:\backup\sourcedir\a\b\
    ::
    :: Or leave the last XCOPY out and this batch will do the same
    :: if you supply the parameter "c:\sourcedir\a\b\text1.txt"
    ::
    :: IE. at the prompt, enter
    ::
    :: thisbatchname "c:\sourcedir\a\b\text1.txt"
    ::
    :: (where the quotes are optional UNLESS the parameter contains 
    ::  a special character or a space"
    ::
    XCOPY "%~1" "u:\backup2%~p1"
    

    The first XCOPY should be obvious.

    The second works by using %~1 which is the first parameter, minus the enclosing quotes (if any) - this is then requoted to ensure the character string produced is parsed as a single string.

    The second parameter to XCOPY strings U:\BACKUP2 together with %~p1 - which is the p - PATH of parameter 1, then quote the whole thing.

    Consequently, the command executed with "c:\sourcedir\a\b\text1.txt" as a parameter would be

    xcopy "c:\sourcedir\a\b\text1.txt" "u:backup2\sourcedir\a\b\"
    

    which creates the destination tree as required.