ファイル名の一部をファイル名の先頭に移動する

ファイル名の一部をファイル名の先頭に移動する

ファイル名の一部をファイル名の先頭に移動したいです。すべてのファイル#には、次のような区切り文字が含まれています2585#xxxxx#4157.pdf

#ここで、ファイル名の最後の部分を 2 番目の部分に移動します。例: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
}

関連情報