【问题标题】:Powershell - rename item in sub foldersPowershell - 重命名子文件夹中的项目
【发布时间】:2021-04-13 15:12:24
【问题描述】:

我是使用 powershell 的新手,我需要一些关于脚本的帮助。

我一直在使用dir | Rename-Item -NewName {$_.Name -replace "Abc_123", "XYZ"} 更改文件夹中的大量文件名,但我想做更多。 我需要从“Alex_Chris_123_456_ABC”更改为“AC_123_456_ABC”。

我想是这样的。

Get-ChildItem -File -Recurse | % { Rename-Item -Path $_.PSPath -NewName $_.Name.replace("Abc_123", "XYZ")}

但这只会改变特定的字符。如何在第一个整数之前添加一个条件语句来获取字符串的第一个字符?

【问题讨论】:

  • 你可以使用"Alex_Chris_123_456_ABC" -replace '^([a-z])[a-z]*_([a-z])[a-z]*','$1$2'
  • 您的文件名格式的可预测性如何?涵盖所有场景可能会变得复杂,例如 [regex]::Replace("Alex_Chris_123_456_ABC",'(?i)^(?:[a-z]+_)+',{(-join ($args[0].Value -split '_' |% {[string]$_[0]}))+'_'}) 适用于 1 个或多个名称,但您需要用下划线分隔名称的各个部分。但是[regex]::Replace("Alex?Cross-123_456_ABC",'(?i)^(?:[a-z]+[^a-z])+',{(-join ($args[0].Value -split '[^a-z]' |% {[string]$_[0]}))+([string]$args[0])[-1]}) 可以用于任何非字母分隔符。
  • 感谢您的回复。文件名有些可预测,因为它们是来自我们处理程序的数据文件。名称用下划线分隔。如何包含正则表达式,以便它读取所有文件、文件夹和子文件夹并重命名它们?
  • 我们还没有收到您的来信.. 我的回答解决了您的问题吗?如果是这样,请通过单击左侧的大复选标记图标 来考虑accepting。这将帮助其他有类似问题的人更轻松地找到它。

标签: powershell rename batch-rename


【解决方案1】:

离你不远了。使用 Rename-Item,在这种情况下您不需要 ForEach-Object 循环,因为NewName 参数还可以采用脚本块来对通过管道发送的每个文件执行操作。

试试

$sourcePath = 'D:\Test'  # change this to the rootfolder where the files and subfolders are
Get-ChildItem -Path $sourcePath -File -Recurse | 
    Where-Object { $_.Name -match '^(\D+)(_.*)' } |  # see regex details below
    Rename-Item -NewName {
        # split on the underscore and join the first characters of each part together
        $prefix = ($matches[1].Split("_") | ForEach-Object { $_.Substring(0,1) }) -join ''
        '{0}{1}' -f $prefix, $matches[2]
    }

正则表达式详细信息:

^             Assert position at the beginning of the string
(             Match the regular expression below and capture its match into backreference number 1
   \D         Match a single character that is not a digit 0..9
      +       Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)            
(             Match the regular expression below and capture its match into backreference number 2
   _          Match the character “_” literally
   .          Match any single character that is not a line break character
      *       Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)

【讨论】:

  • @Jay 你为什么不接受这个答案?有什么不工作?请解释一下。
猜你喜欢
  • 2017-03-17
  • 1970-01-01
  • 2015-10-26
  • 1970-01-01
  • 2017-07-10
  • 2014-04-14
  • 2017-06-09
  • 1970-01-01
  • 2021-04-10
相关资源
最近更新 更多