0

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.

2 Answers2

1

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • This worked! Thanks. Can you explain exactly what's going on here? Still trying to learn. – user3194848 Jan 14 '14 at 22:54
  • 1
    @user3194848 BTW, the question is ambiguous...the example in the beginning implies that you want to replace **345** with **302**, but what you say at the end implies that you want to keep the same number (which is what the regex in this answer does). Was the **302** a typo? If you really do want to change the number, change the replace to `$_.Name -replace '^(.*) (\S+) ([^.]+)', '$2 $1 302'`. – Adi Inbar Jan 15 '14 at 01:40
0

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;
};
  • This one didn't work. I got an error "You cannot call a method on a null-valued expression" on the split operator. – user3194848 Jan 14 '14 at 22:54
  • What version of PowerShell are you using? `$PSItem` is new as of PowerShell version 3.0, so if you're running PowerShell version 2.0, then you'll have to use `$_` instead of `$PSItem`. –  Jan 14 '14 at 23:35