
我想將檔案名稱的一部分移到檔案名稱的前面。我的所有文件#
中都有一個分隔符,例如:2585#xxxxx#4157.pdf
。
現在我想將檔案名稱最後一個部分之後的部分移動#
到檔案名稱的第二部分,例如:2585#4157#xxxxx.pdf
我怎麼才能用 powershell 做到這一點?我自己還沒有研究過任何方法,因為我不知道要搜尋什麼。
答案1
下面的腳本將滿足您的需求。它是用不太簡潔的循環編寫的,因此每一步都清晰可見。有更優化的方法來編寫此腳本。
# Assumes this script is run in the directory with the pdf files
# First get all pdf files in the current directory
$all_files = Get-ChildItem -Path . -Filter '*.pdf'
# Loop over all files
foreach ($file in $all_files) {
# Get the current (old) filename
$old_name = $file.Name
# Define a regex pattern (see below)
$regex_pattern = '(.+)#(.+)#(.+)(\.pdf)'
# Define a replacement pattern (see below)
$replace_pattern = '$1#$3#$2$4'
# Construct the new name
$new_name = $old_name -replace $regex_pattern, $replace_pattern
# Actually rename the file
Rename-Item -Path $file.FullName -NewName $new_name
}
正規表示式
正規表示式是一種搜尋(和替換)文字的高級方法。
搜尋模式可以分為以下幾個部分:
(.+) Match any character 1 or more times, store in the first group
# Match the # symbol literally
(.+) Match any character 1 or more times, store in the second group
# Match the # symbol literally
(.+) Match any character 1 or more times, store in the third group
(\.pdf) Match a literal dot followed by the letters "pdf" and store in the fourth group
替換模式使用搜尋模式中的儲存部分重新排序:
$1 Take the content from the first group
# Write a literal # symbol
$3 Take the content from the third group
# Write a literal # symbol
$2 Take the content from the second group
$4 Take the content from the fourth group
執行此腳本會重新命名以下檔案:
2585#xxxxx#4157.pdf
2d23#ab23-421d#40++057.pdf
2d23#abd#400057.pdf
進入
2585#4157#xxxxx.pdf
2d23#40++057#ab23-421d.pdf
2d23#400057#abd.pdf
答案2
作為沒有正規表示式的替代方案,您可以這樣做:
(Get-ChildItem -Path 'X:\where\the\files\are' -Filter '*#*#*.pdf' -File) |
Rename-Item -NewName {
$first, $second, $third = $_.BaseName.Split("#")
'{0}#{1}#{2}{3}' -f $first, $third, $second, $_.Extension
}