我在一個檔案夾中有許多檔案,如下所示:
- 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
}
}
uj5u.com熱心網友回復:
這將通過將檔案中的所有下劃線替換為破折號來重命名檔案,最后一個下劃線除外:
(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
uj5u.com熱心網友回復:
如果要在重命名檔案時保留最后一個下劃線,請使用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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/389930.html
