【问题标题】:Renaming multiple directory names with regex using powershell使用 powershell 使用正则表达式重命名多个目录名称
【发布时间】:2021-09-08 18:22:43
【问题描述】:

我在某个时候卡住了。 假设以下目录:

d:\example
             0 test1_123.txt
<DIR>          test1_123_abc0
             0 test2.txt
<DIR>          test2_123
<DIR>          test3_123_abc1
<DIR>          test4_test0_abc0

我现在想使用正则表达式“_abc*”删除所有目录名称的后缀。我尝试了以下方法:

Get-ChildItem d:\example\ -Directory | foreach { rename-item $_ $_ -replace '_abc.' }

有人知道这里出了什么问题并可以分享解决方案吗?

【问题讨论】:

  • 试试Get-ChildItem 'd:\example\' -Recurse -Filter *_abc* | Rename-Item -NewName { $_.name -replace '_abc\d*$', ''}
  • 你怎么看这个 >>> { rename-item $_ $_ -replace '_abc.' } grin] 这两个 $_ 项目看起来非常错误......
  • 另外,当截断一个目录名使其成为另一个目录名时,你想如何处理欺骗目录名?

标签: regex powershell directory


【解决方案1】:

这是解决问题的一种方法... [grin]

它的作用...

  • 创建一些文件和目录来测试
    当准备好真正执行此操作时,只需删除整个 #region/#endregion 块。
  • 设置目标目录、目录过滤器和正则表达式删除模式
    如果您还想删除末尾不带任何数字的_abc,请将+ [一个或多个] 替换为* [零个或多个]。
  • 获取匹配目录列表
  • 遍历该列表
  • 通过剥离与正则表达式匹配的结尾来重命名目录

请注意,这不处理名称冲突。如果您两次运行此代码,您将看到 test5_abc666 重命名为 test5 ... 并且具有该名称的目录已经存在。 [咧嘴一笑]

代码...

#region >>> make some test files & dirs
@(
'test1_123.txt'
'test2.txt'
'test3_abc9.log'
) | ForEach-Object {
    $Null = New-Item -Path $env:TEMP -Name $_ -ItemType File -ErrorAction SilentlyContinue
    }
@(
'test1_123_abc0'
'test2_123'
'test3_123_abc1'
'test4_test0_abc0'
'test5_abc666'
) | ForEach-Object {
    $Null = New-Item -Path $env:TEMP -Name $_ -ItemType Directory -ErrorAction SilentlyContinue
    }
#endregion >>> make some test files & dirs

$TargetDir = $env:TEMP
$Filter = '*_abc*'
$Regex_ThingToRemove = '_abc\d+$'

$DirList = Get-ChildItem -LiteralPath $TargetDir -Directory -Filter $Filter
foreach ($DL_Item in $DirList)
    {
    Rename-Item -LiteralPath $DL_Item.FullName -NewName ($DL_Item.Name -replace $Regex_ThingToRemove)
    }

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2018-07-30
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2020-08-03
    相关资源
    最近更新 更多