Как рекурсивно копировать файлы с помощью командной строки Windows

2415
Mike Godin

Я хотел бы избежать использования командного файла, если это возможно.

Основываясь на этом ответе на вопрос о рекурсивном переименовании или перемещении, я придумал следующую команду (для копирования всех файлов с именем web.foo.config в web.config в одном каталоге ):

for /r %x in (*web.foo.config) do copy /y "%x" web.config 

Однако это просто вызвало создание каждого экземпляра web.foo.config с последующей перезаписью. \ Web.config, а не web.config в найденном пути. Итак, я попробовал:

for /r %x in (*web.foo.config) do (SET y=%x:foo.config=config% && CALL copy /y "%x" "%y") 

К сожалению, это приводит к копированию файлов в файл с именем «% y». Есть ли способ заставить %yбыть оцененным после его установки ... или лучший метод в целом?

1

1 ответ на вопрос

1
Pimp Juice IT

Copying all files named web.foo.config to web.config in the same directory

Since you don't want to use a batch file for this operation then from an elevated command prompt, you can use the below to complete this.

This assumes the directory you are in when you run the command from the command prompt is the one which will be traversed through recursively doing the copy command of the found files.

I left the asterisk (*) from the beginning of the web.foo.config file name but you can add that where needed if it's really needed to find files with that naming pattern.

Using Copy Example

FOR /F "TOKENS=*" %F IN ('DIR /B /S web.foo.config') DO COPY /Y "%~F" "%~DPFweb.config"

Using Xcopy Example

FOR /F "TOKENS=*" %F IN ('DIR /B /S web.foo.config') DO ECHO F | XCOPY /Y /F "%~F" "%~DPFweb.config"

Further Resources

  • FOR /F
  • FOR /?

    In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

    %~I - expands %I removing any surrounding quotes (")
    %~fI - expands %I to a fully qualified path name
    %~dI - expands %I to a drive letter only
    %~pI - expands %I to a path only
    %~nI - expands %I to a file name only
    %~xI - expands %I to a file extension only
    %~sI - expanded path contains short names only
    %~aI - expands %I to file attributes of file
    %~tI - expands %I to date/time of file
    %~zI - expands %I to size of file
    %~$PATH:I - searches the directories listed in the PATH
     environment variable and expands %I to the
     fully qualified name of the first one found.
     If the environment variable name is not
     defined or the file is not found by the
     search, then this modifier expands to the
     empty string
    
Спасибо, намного лучше, чем решение, которое я собирался опубликовать: `FOR / R% x IN (* web.foo.config) DO FOR / F" delims =. " % y IN ("% x") DO COPY / Y "% x" "% y.config" `, который работает, пока в пути нет периодов. Mike Godin 7 лет назад 2