Вопрос

I have a large number of files in a directory with this type of naming convention: "[Date] [Lastname] 345.pdf". Note: the 345 is constant for all of them

I would like to rename all of the files so that they read "[Lastname] [Date] 345.pdf".

Edit: I had a typo in there initially

I have had some success with:

gci -Filter *.pdf| %{Rename-Item $_.fullname $_.Name.Split(" ")[1]}

But that only gives me "[Date].pdf". Basically, I can't figure out how to use the above command to combine two different parts of the split. I basically want "[1] [0] [2].pdf" if that makes any sense.

Thanks.

Это было полезно?

Решение

Another approach, using regular expressions:

Get-ChildItem *.pdf | % {
  $newName = $_.Name -replace '^(.*) (\S+) (\S+\.pdf)$', '$2 $1 $3'
  Rename-Item $_ $newName
}

Regular expression breakdown:

  • ^(.*) matches any number of characters at the beginning of the string and captures them in a group. [Date] in your example filename [Date] [Lastname] 345.pdf.
  • (\S+) matches one or more consecutive non-whitespace characters and captures them in a second group. [Lastname] in your example filename [Date] [Lastname] 345.pdf.
  • (\S+\.pdf)$ matches one or more consecutive non-whitespace characters followed by the string .pdf at the end of the string and captures that in a third group. 345.pdf in your example filename [Date] [Lastname] 345.pdf.

The groups are referred to by $1, $2 and $3, so the replacement string '$2 $1 $3' re-orders the groups the way you want.

Другие советы

Give this a shot.

gci *.pdf| %{
    $Name = $PSItem.Name.Split(' ');
    $Dest = ('{0} {1} {2}' -f $Name[1], $Name[0], $Name[2]);
    Move-Item $PSItem.FullName -Destination $Dest;
};
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top