从文件夹名称中删除额外的方括号



我有一系列文件夹,命名如下

[[1254170]][folder1]
[[1212340]][folder2]
[[3245417]][folder3]

我想把它们都重命名为

[1254170]folder1
[1212340]folder2
[3245417]folder3

或至少

[1254170][folder1]
[1212340][folder2]
[3245417][folder3]

我编辑了批处理命令,这是我从一年前的一个问题中学到的。

Get-ChildItem -path . -directory -recurse | Where {$_.Name -match '^[[d]]'} | Rename-Item -NewName {$_.Name -replace '^[[d]]','^[d]'}

命令通过了,但是什么也没发生。

我还从这个答案中尝试了一个编辑版本的命令

Get-ChildItem * -Filter "*`[`[*`]`]*" | Rename-Item -NewName { $_.name -replace '[[','[' -replace ']]',']' }

我得到了这个错误

Rename-Item : Cannot rename the specified target, because it represents a path or device name.
At line:1 char:41
+ ... `[*`]`]*" | Rename-Item -NewName { $_.name -replace '[[','[' -repl ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [Rename-Item], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand

谁来帮帮我?我用的是Windows 11。谢谢你。

$path = "D:test"
Get-ChildItem $path -Filter "`[`[*`]`]`[*`]" -Directory|ForEach{
Rename-Item -Literal $_.FullName $_.Name.Replace("[[","[").Replace("]]","]")
}
  • 使用Where-Object-match操作查找感兴趣的文件夹(目录)名称,通过regex捕获组((...))捕获感兴趣的子字符串。

  • 您可以将匹配的文件夹管道到Rename-Item,并使用延迟绑定脚本块来动态确定新名称,其中您可以通过自动$Matches变量引用捕获的子字符串。

    • 在延迟绑定脚本块中,您可以使用-f(字符串格式化操作符)来合成新名称。
Get-ChildItem -Directory -Recurse |
Where-Object Name -match '^[[(.+?)]][(.+?)]$' | 
Rename-Item -NewName { '[{0}]{1}' -f $Matches[1], $matches[2] } -WhatIf

备注:上面命令中的-WhatIfcommon参数预览操作。删除-WhatIf,一旦你确定操作将做你想要的。

$testinput = '[[1254170]][folder1]'
$testinput
## catch the string and replace using regex
### replacing the matched string with capture group 2
$testinput -replace '([)(.*?)(])', '${2}'
$testinput

C:> [1254170]folder1

正则表达式解释
( open capture group 1
 escaping the next character
[ matches [ literally
) closing capture group 1
( starting capture group 2
. matching any character except line breaks
* matches 0 or more of the preceding .
? making this lazy to capture as few as possible
) closing capture group 2

( starting capture group 3
 escaping the next character
] matches ] literally
) closing capture group 3
([)(.*?)(])
( [ )( [1254170] )( ] )  ( [ )( folder1 )( ] )
( 1 )(    2      )( 3 )  ( 1 )(    2    )( 3 )

后一个[123123][folder1]我是这样得到的:

$str = '[[1254170]][folder1]'
$newstr = ($str | select-string '[[w-]+]?').Matches.Value + ($str | select-string '[[w-]+]+$').Matches.Value

$newstr
[1254170][folder1]

最新更新