批量重命名文件并保留最后一个破折号
Posted
技术标签:
【中文标题】批量重命名文件并保留最后一个破折号【英文标题】:batch rename files and keep the last dash 【发布时间】:2022-01-22 12:10:20 【问题描述】:我在一个文件夹中有很多文件,如下所示:
E123_1_410_4.03_97166_456_2.B.pdf E123-1-410-4.03-97166-456_2.B.pdf我可以更改所有下划线,但不能只更改其中的 5 个。
$names = "AD1-D-1234-3456-01","111-D-abcd-3456-01","abc-d-efgi-jklm-no","xxx-xx-xxxx-xxxx-xx"
$names |
ForEach-Object
$new = $_ -replace '(?x)
^ # beginning of string
( # begin group 1
[^-]3 # a pattern of three non-hyphen characters
) # end of group 1
- # a hyphen
( # begin group 2
[^-] # a non-hyphen (one character)
- # a hyphen
[^-]4 # a pattern of non-hyphen characters four characters in length
- # a hyphen
[^-]4 # a pattern of non-hyphen characters four characters in length
) # end of group 2
- # a hyphen
( # begin group 3
[^-]2 # a pattern of non-hyphen characters two characters in length
) # end of group 3
$ # end of string
', '$1_$2_$3' # put the groups back in order and insert "_" between the three groups
if ($new -eq $_) # check to see if the substitution worked. I.e., was the pattern in $_ correct
Write-Host "Replacement failed for '$_'"
else
$new
【问题讨论】:
【参考方案1】:这将通过将文件中的所有下划线替换为破折号来重命名文件,除了是最后一个下划线:
(Get-ChildItem -Path 'X:\Where\The\Files\Are' -Filter '*_*.*' -File) | Rename-Item -NewName
$prefix, $postfix = $_.Name -split '^(.+)(_[^_]+)$' -ne ''
"0$postfix" -f ($prefix -replace '_', '-')
-WhatIf
我已将Get-ChildItem
放在括号内,让它先完成收集文件。如果您忽略它,它可能会拾取已重命名的文件,这是浪费时间。
添加的开关_WhatIf
是一个安全装置。这让您可以在控制台窗口中看到代码将重命名的内容。如果您认为这是正确的,请移除 -WhatIf
开关并再次运行代码,以便实际重命名文件。
例子:
X:\Where\The\Files\Are\111_D_abcd_3456_01_qqq_7C.pdf --> X:\Where\The\Files\Are\111-D-abcd-3456-01-qqq_7C.pdf
X:\Where\The\Files\Are\AD1_D-1234_3456-01_xyz_3.A.pdf --> X:\Where\The\Files\Are\AD1-D-1234-3456-01-xyz_3.A.pdf
X:\Where\The\Files\Are\E123_1_410_4.03_97166_456_2.B.pdf --> X:\Where\The\Files\Are\E123-1-410-4.03-97166-456_2.B.pdf
【讨论】:
【参考方案2】:如果您想在重命名文件时保留最后一个下划线,请使用 split 解构部分单词,并使用循环重构名称。最后加上破折号。这样无论下划线有多少个,都可以全部替换。
工作代码:
$names = "E123_1_410_4.03_97166_456-test-test_2.pdf", "E123_1_410_4.03_97166_456_2.B.pdf"
$names |
ForEach-Object
$new = [string]::empty;
#split
$tab = $_.split("_");
#do nothing if there is only one or no dash
if($tab.count -gt 2)
#reconstruct by using keep a dash at the end
$new = $tab[0];
for($i = 1; $i -lt $tab.count - 1; $i++)
$txt = $tab[$i];
$new += "-" + $txt ;
#add last dash
$txt = $tab[$tab.count - 1];
$new += "_" + $txt;
if ($new -eq $_) # check to see if the substitution worked. I.e., was the pattern in $_ correct
Write-Host "Replacement failed for '$_'"
else
write-Host $new;
【讨论】:
以上是关于批量重命名文件并保留最后一个破折号的主要内容,如果未能解决你的问题,请参考以下文章