Einen Teil des Dateinamens an den Anfang des Dateinamens verschieben

Einen Teil des Dateinamens an den Anfang des Dateinamens verschieben

Ich möchte einen Teil des Dateinamens an den Anfang des Dateinamens verschieben. Alle meine Dateien enthalten ein Trennzeichen #, beispielsweise: 2585#xxxxx#4157.pdf.

Nun möchte ich den nachletzten Teil #in den zweiten Teil des Dateinamens verschieben, zB:2585#4157#xxxxx.pdf

Wie kann ich das mit Powershell machen? Ich habe mir selbst noch keine Methoden angeschaut, da ich nicht weiß, wonach ich suchen soll.

Antwort1

Das folgende Skript erledigt das, was Sie suchen. Es ist in einer nicht allzu prägnanten Schleife geschrieben, sodass jeder Schritt klar ist. Es gibt bessere Möglichkeiten, dies zu skripten.

# 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
}

Regulärer Ausdruck

Regulärer Ausdruckist eine erweiterte Möglichkeit zum Suchen (und Ersetzen) von Text.

Das Suchmuster kann in folgende Teile zerlegt werden:

(.+)      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

Das Ersetzungsmuster ordnet die gespeicherten Teile anhand des Suchmusters neu an:

$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

Durch Ausführen dieses Skripts werden die folgenden Dateien umbenannt:

2585#xxxxx#4157.pdf
2d23#ab23-421d#40++057.pdf
2d23#abd#400057.pdf

hinein

2585#4157#xxxxx.pdf
2d23#40++057#ab23-421d.pdf
2d23#400057#abd.pdf

Antwort2

Als Alternative ohne reguläre Ausdrücke können Sie Folgendes tun:

(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
}

verwandte Informationen