【问题标题】:Batch rename and copy multiple files in Windows在 Windows 中批量重命名和复制多个文件
【发布时间】:2019-03-16 13:59:33
【问题描述】:

我在同一个文件夹中有大量类似名称的文件:

  • myPic_fr.png
  • myPic_it.png
  • myPic_gr.png

我想将它们重命名为:

  • myPic_fr_1080.png
  • myPic_it_1080.png
  • myPic_gr_1080.png

然后将它们复制到这样的新文件夹中:

  • ../fr/myPic_fr_1080.png
  • ../it/myPic_it_1080.png
  • ../gr/myPic_gr_1080.png

如何创建批处理脚本或 powershell 脚本来完成这项工作?

编辑: 我试过这个批处理脚本代码来做重命名工作(Thanks @RoXX):

@echo off
setlocal EnableDelayedExpansion
SET oldPart=.png
SET newPart=_1080.png
for /f "tokens=*" %%f in ('dir /b *.png') do (
  SET newname=%%f
  SET newname=!newname:%oldPart%=%newPart%!
  move "%%f" "!newname!"
)

但是对于“复制”部分,我不知道该怎么做!也许需要正则表达式?

谢谢

【问题讨论】:

  • 您需要只在目标文件夹中重命名它们,还是在两个地方都重命名?
  • 我会先尝试阅读文档:Get-ChildItemCopy-ItemRename-Item,然后尝试自己编写一些代码。如果/当您在代码中遇到任何问题时,请说明您尝试了哪些方法,以及为什么它对您不起作用。
  • 在这两个地方。
  • 您对批处理文件进行了过度编码。阅读FOR 命令的帮助文件的最后一部分。从文件名中去除文件扩展名非常容易,而无需进行字符串替换。

标签: powershell batch-file powershell-v5.1


【解决方案1】:

之前的样本树

> tree /f
    myPic_fr.png
    myPic_gr.png
    myPic_it.png

运行此脚本:

## Q:\Test\2018\10\11\SO_52760856.ps1
Get-ChildItem *_*.png | Where-Object BaseName -match '^.*_([^_]{2})$' | 
  ForEach-Object {
    $Country=$Matches[1]
    $NewName=$_.BaseName+"_1080"+$_.Extension
    $_ | Rename-Item -NewName $NewName
    if (!(Test-Path $Country)){MD $Country|Out-Null}
    Copy-Item  $NewName (Join-Path $Country $newName)  
  }

之后的树

> tree /f
│   myPic_fr_1080.png
│   myPic_gr_1080.png
│   myPic_it_1080.png
│
├───fr
│       myPic_fr_1080.png
│
├───gr
│       myPic_gr_1080.png
│
└───it
        myPic_it_1080.png

【讨论】:

  • 非常感谢@lotpings ? 还有一件事,如何匹配 myPic_02_fr.png 这种格式的文件名?
  • 为了避免多次运行脚本时出现问题,我选择了一个正则表达式来选择只需要 one 下划线的国家/地区。 @Esperento57 使用的方式通过选择最后一个下划线分隔的标记来避免这种情况。我将修改我的正则表达式,使其在一分钟内对下划线的数量不特定 - DONE
  • 完美!再次感谢?
【解决方案2】:

这远非最佳,但您可以尝试以下方法:

foreach ($pic in (Get-ChildItem *.png -Name)) {
    # delete "myPic_" and ".png" to get the destination-folder from the filename
    $destFolder = ($pic -replace "myPic_", "") -replace "`.png", ""
    # replace ".png" with "_1080.png" to create the new filename
    $destName = $pic -replace ".png", "_1080.png"

    Copy-Item "$pic" "$destFolder\$destName"
}

【讨论】:

    【解决方案3】:

    试试这个

    Get-ChildItem "C:\temp\test" -file -Filter "?*_?*.png" | %{
    
    $NewName="{0}_1080{1}" -f $_.BaseName, $_.Extension
    $NewDir="{0}\{1}" -f $_.DirectoryName, ($_.BaseName -split "_")[-1]
    $NewPath="{0}\{1}" -f $NewDir, $NewName
    
    New-Item $NewDir -ItemType Directory -Force
    Copy-Item $_.FullName -Destination $NewPath -Force -Recurse
    Rename-Item $_.FullName -NewName $NewName
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 2016-04-09
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多