Batch rename files in a directory by changing filenames
I have a large number of files in a directory with this type of naming convention: "[Date] [Lastname] 345.pdf". Note: 345 is constant for all of them
I would like to rename all files so that they read "[Lastname] [Date] 345.pdf".
Edit: I had a typo there
I've had some success:
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 split pieces. I basically want "[1] [0] [2] .pdf" if that makes sense.
Thank.
source to share
Another approach using regular expressions:
Get-ChildItem *.pdf | % {
$newName = $_.Name -replace '^(.*) (\S+) (\S+\.pdf)$', '$2 $1 $3'
Rename-Item $_ $newName
}
Regular Expression Distribution:
-
^(.*)
matches any number of characters at the beginning of a line and commits them to a group.[Date]
in your example filename[Date] [Lastname] 345.pdf
. -
(\S+)
matches one or more characters without spaces and captures them in the second group.[Lastname]
in your example the filename[Date] [Lastname] 345.pdf
. -
(\S+\.pdf)$
matches one or more consecutive non-whitespace characters, followed by a line.pdf
at the end of the line, and captures this in the third group.345.pdf
in your example filename[Date] [Lastname] 345.pdf
.
The groups are named $1
, $2
and $3
so the replacement string '$2 $1 $3'
reorders the groups the way you want.
source to share