Mover parte del nombre del archivo al frente del nombre del archivo

Mover parte del nombre del archivo al frente del nombre del archivo

Quiero mover una parte del nombre del archivo al frente del nombre del archivo. Todos mis archivos tienen un delimitador #, como por ejemplo: 2585#xxxxx#4157.pdf.

Ahora quiero mover la parte después de la última #a la segunda parte del nombre del archivo, por ejemplo:2585#4157#xxxxx.pdf

¿Cómo puedo hacer eso con powershell? Todavía no he investigado ningún método porque no sé qué buscar.

Respuesta1

El siguiente script hará lo que estás buscando. Está escrito en un bucle no tan conciso, de modo que cada paso del camino queda claro. Hay formas más óptimas de escribir esto.

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

expresión regular

expresión regulares una forma avanzada de buscar (y reemplazar) texto.

El patrón de búsqueda se puede dividir en las siguientes partes:

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

El patrón de reemplazo utiliza reordenamientos de las piezas almacenadas desde el patrón de búsqueda:

$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

Al ejecutar este script se cambia el nombre de los siguientes archivos:

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

en

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

Respuesta2

Como alternativa sin expresiones regulares, puedes hacer esto:

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

información relacionada