我正在尝试使用 PowerShell 批量复制和重命名文件。
原始文件名为AAA001A.jpg、AAB002A.jpg、AAB003A.jpg等。
我想用新名称复制文件,方法是从文件名中删除前四个字符以及句点之前的字符,以便复制的文件被命名为 01.jpg、02.jpg、03.jpg 等。
我有在 Linux 上使用 Bash 脚本的经验,但我对如何使用 PowerShell 执行此操作感到困惑。经过几个小时的反复试验,这是我所得到的最接近的结果:
Get-ChildItem AAB002A.jpg | foreach { copy-item $_ "$_.name.replace ("AAB","")" }
(它不起作用)
Note:
* While perhaps slightly more complex than abelenky's answer https://stackoverflow.com/a/42127151/45375, it (a) is more robust in that it ensures that only *.jpg
files that fit the desired pattern are processed, (b) shows some advanced regex techniques, (c) provides background information and explains the problem with the OP's approach.
* This answer uses PSv3+ syntax.
Get-ChildItem *.jpg |
Where-Object Name -match '^.{4}(.+).\.(.+)$' |
Copy-Item -Destination { $Matches.1 + '.' + $Matches.2 } -WhatIf
To keep the command short, the destination directory is not explicitly controlled, so the copies will be placed in the current dir. To ensure placement in the same dir. as the input files, use
Join-Path $_.PSParentPath ($Matches.1 + '.' + $Matches.2)
inside { ... }
.
-WhatIf
previews将复制到哪些文件;删除它以执行实际复印。
Get-ChildItem *.jpg
输出全部*.jpg
文件 - 它们是否符合要重命名的文件的模式。
-
Where-Object Name -match '^.{4}(.*).\.(.+)$'
然后使用regex(正则表达式):
-
^...$
锚定正则表达式以确保它与whole input (^
匹配输入的开头,并且$
其结束)。
-
.{4}
匹配第一个4
人物 (.
),无论它们是什么。
-
(.+)
匹配任何非空字符序列,并且由于包含在(...)
,捕获该序列捕获组,这反映在自动$Matches
变量,可访问为$Matches.1
(由于是第一个捕获组)。
-
.
匹配文件扩展名之前的字符。
-
\.
匹配一个literal .
,由于逃脱了\
- 即扩展的开始。
-
(.+)
是捕获文件扩展名的第二个捕获组(没有前面的.
字面意思),可访问为$Matches.2
.
-
Copy-Item -Destination { $Matches.1 + '.' + $Matches.2 }
然后根据从输入文件名中提取的捕获组值重命名每个输入文件。
一般来说,如果可行的话,直接通过管道传输到 cmdlet 总是比通过管道传输到Foreach-Object
cmdlet(其内置别名是foreach
),出于性能原因。
In the Copy-Item
上面的命令,目标路径是通过脚本块参数,对每个输入路径进行评估$_
绑定到手头的输入文件。
-
注意:以上假设副本应放置在current目录,因为脚本块仅输出一个filename, not a path.
- 要显式控制目标路径,请使用
Join-Path
在 - 的里面-Destination
脚本块。
例如,确保副本始终放置在与输入文件相同的文件夹中 - 无论当前目录是什么。是 - 使用:
Join-Path $_.PSParentPath ($Matches.1 + '.' + $Matches.2)
As for 你尝试过什么:
Inside "..."
(双引号字符串),您必须使用$(...)
, the 子表达式运算符,以便嵌入应替换为其值的表达式。
不管怎样,.replace ("AAB", "")
(a) 由于空格字符而导致语法中断。前(
(你是否混淆了[string]
type's .Replace()
method使用 PowerShell 的-replace
operator?), (b) 硬编码要删除的前缀,(c) 仅限于3字符,并且 (d) 不会删除句点之前的字符。
目的地位置警告也适用:如果你的表达式有效,它只会计算为filename,这会将生成的文件放入current目录而不是与输入文件相同的目录(尽管这不会成为问题,如果您从当前目录运行命令,或者如果这是您的实际意图)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)