如何使用Windows命令行递归复制和重命名同一目录中的文件

Mik*_*din 5 windows command-line recursive

如果可能的话,我想避免使用批处理文件。

基于对有关递归重命名或移动的问题的回答,我想出了以下命令(用于将所有名为 web.foo.config 的文件复制到同一目录中的web.config ):

for /r %x in (*web.foo.config) do copy /y "%x" web.config
Run Code Online (Sandbox Code Playgroud)

但是,这只会导致 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")
Run Code Online (Sandbox Code Playgroud)

这会产生将文件复制到名为“%y”的文件的不幸效果。有没有一种方法可以%y在设置后强制进行评估...或者完全是更好的方法?

小智 5

使用带有 /S 开关的 xcopy 递归复制所有文件和目录。

在任何 Windows 命令提示符下:

xcopy *.* \destination /S
Run Code Online (Sandbox Code Playgroud)

快捷方便。


Vom*_*yle 2

将所有名为 web.foo.config 的文件复制到同一目录中的 web.config

由于您不想在提升的命令提示符下使用批处理文件来执行此操作,因此您可以使用以下命令来完成此操作。

这假设您从命令提示符运行命令时所在的目录是通过递归执行找到的文件的复制命令来遍历的目录。

*我在文件名的开头留下了星号 ( ) web.foo.config,但如果确实需要查找具有该命名模式的文件,您可以在需要的地方添加它。

使用复制示例

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

使用 Xcopy 示例

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

更多资源

  • 对于/F
  • FOR /?

    此外,FOR 变量引用的替换也得到了增强。您现在可以使用以下可选语法:

    %~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
    
    Run Code Online (Sandbox Code Playgroud)

  • 谢谢,比我要发布的解决方案要好得多: `FOR /R %x IN (*web.foo.config) DO FOR /F "delims=." %y IN ("%x") DO COPY /Y "%x" "%y.config"`,只要路径中没有句点,它就可以工作。 (2认同)