如何让“dir”和“copy”命令对“*.xyz”而不是“*.xyz~”进行操作?

pau*_*doo 4 windows cmd.exe

当我使用copy *.txt somefolder\系统时,似乎也复制了所有*.txt~文件,这不是我想要的。可以看到类似的相同效果dir

C:\Users\Paul\Documents\Programs\Proffy>dir *.txt
 Volume in drive C is Vista
 Volume Serial Number is EC23-AD6B

 Directory of C:\Users\Paul\Documents\Programs\Proffy

29/11/2008  13:54            35,821 COPYING.txt
31/10/2009  21:54             1,644 INSTRUCTIONS.txt
06/06/2009  15:57             1,393 INSTRUCTIONS.txt~
04/01/2009  11:59               116 Notes.txt
19/04/2009  16:53               134 README.txt
04/01/2009  12:42               132 README.txt~
31/10/2009  21:30               197 TODO.txt
31/10/2009  19:10               414 TODO.txt~
               8 File(s)         39,851 bytes
               0 Dir(s)  41,938,862,080 bytes free

C:\Users\Paul\Documents\Programs\Proffy>
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得dircopy只对以 结尾.txt和 不结尾的文件进行操作.txt~

Joe*_*oey 5

显然,shell 考虑了通配符扩展的短名称长名称。可以在shf301's answer 中找到更长的解释。这是不幸的,并且可能是 DOS 的 Ye Olde Days 的遗留物,因为这cmd毕竟是试图与(某种程度上)兼容的。

这里有几个选项:

  1. 使用forfiles,它对通配符扩展具有不同的语义:

    forfiles /m *.txt /c "cmd /c copy @file foo"
    
    Run Code Online (Sandbox Code Playgroud)

    这至少在 Vista 及更高版本上可用。

  2. 使用for并检查扩展名:

    for %a in (*.txt) do @if %~xa==.txt @copy "%i" foo
    
    Run Code Online (Sandbox Code Playgroud)

    不幸的是for.txt~当仅使用通配符扩展时,也会返回带有扩展名的任何文件。这就是为什么我们需要第二次检查扩展。

  3. 使用xcopy. 虽然xcopy通配符扩展的语义与 shell 相同,但您可以给它一个文件名以忽略:

    echo .txt~>tmpfile
    xcopy *.txt foo /exclude:tmpfile
    del tmpfile
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使用robocopy. 虽然robocopy通配符扩展的语义与 shell 相同,但您可以给它一个要忽略的文件/通配符列表:

    robocopy . foo *.txt /XF *.txt~
    
    Run Code Online (Sandbox Code Playgroud)
  5. 使用for,dirfindstr适当组合。这基本上只是过滤掉所有~末尾有 a 的行,然后对其余行进行操作。if我认为上面的变体更优雅。

    for /f "usebackq delims=" %i in (`dir /b *.txt ^| findstr /r "[^~]$"`) do @copy "%i" foo
    
    Run Code Online (Sandbox Code Playgroud)
  6. 只是为了完整性:PowerShell:

    Copy-Item *.txt foo
    
    Run Code Online (Sandbox Code Playgroud)