Powershell重命名文件添加括号

时间:2020-01-05 14:45:56

标签: powershell

我有不同的文件,现在称为455668446854,例如,每个文件都有其自己的编号。 我需要做的是将文件重命名为此: [455] [668] [446854]

通过Powershell做到这一点的最佳方法是什么? 我在同一目录中有几个100个文件,都需要转换。

3 个答案:

答案 0 :(得分:2)

如果您当前位于包含文件的目录中,则可以执行以下操作:

Map

删除Get-ChildItem -Path .\[0-9]*[0-9] -File | Where Name -match '^\d+$' | Rename-Item -NewName {$_.Name -replace '(\d{3})(\d{3})(\d+)','[$1][$2][$3]'} -WhatIf 参数以进行重命名操作。

说明:

Get-ChildItem -WhatIf参数支持通配符。 -Path的目的是查找当前目录(.\[0-9]*[0-9]),并找到以数字开头和结尾的项目。 .仅返回文件。这仅仅是为了最小化效率较低的-File语句的工作。

在这种情况下,

Where是与^\d+$运算符结合使用的正则表达式。它仅表示返回文件,其名称以(-match)开头(一个或多个(^)数字(+)并以这些数字后面(\d)结尾。 / p>

$Name属性应在此处匹配,因为您的帖子中没有文件扩展名。如果您确实具有文件扩展名,则将需要使用BaseName属性。

BaseName操作将三个数字(-replace),三个数字以及其余数字替换为方括号。由于我们在正则表达式机制周围使用\d{3},因此我们从左到右创建了名为1,2,3的捕获组。替换字符串使我们可以对输出进行某种程度的限制(仅Windows PowerShell,因为Core具有更多选项)。

答案 1 :(得分:0)

这仅适用于字符串...如果您使用实际的.BaseName对象,则需要使用fileinfo属性。它同时使用连字符(比方括号更安全的文件名)和方括号。 [咧嘴]

该代码演示了3种方法作为注释列表。

$InStuff = '111222333333'

'using the "-f" format string operator ...'
'{0:###-###-######}' -f [int64]$InStuff
'{0:[###][###][######]}' -f [int64]$InStuff
'=' * 30
'using the "-replace" operator with a regex pattern ...'
$InStuff -replace '(\d{3})(\d{3})(\d{6})', '$1-$2-$3'
$InStuff -replace '(\d{3})(\d{3})(\d{6})', '[$1][$2][$3]'
'=' * 30
# do the insert last-first to avoid changing the the insert position
'using the ".Insert()" string method ...'
$InStuff.Insert(6, '-').Insert(3, '-')
$InStuff.Insert(12, ']').Insert(6, '[').Insert(6, ']').Insert(3, '[').Insert(3, ']').Insert(0, '[')
''

输出...

using the "-f" format string operator ...
111-222-333333
[111][222][333333]
==============================
using the "-replace" operator with a regex pattern ...
111-222-333333
[111][222][333333]
==============================
using the ".Insert()" string method ...
111-222-333333
[111][222][333333]

答案 2 :(得分:0)

您正在寻找子串方法您可以尝试以下方法:

Get-ChildItem -Path "FolderPath" | Foreach {
  $p1 = $_.Name.ToString().SubString(0,3)
  $p2 = $_.Name.ToString().SubString(3,3)
  $p3 = $_.Name.ToString().SubString(6,6)
  Rename-Item -Path $_ -NewName "`[$($p1)`]`[$($p2)`]`[$($p3)`]"
}