Home > front end >  How to rename/rearrange file names in Windows 11?
How to rename/rearrange file names in Windows 11?

Time:07-20

I had multiple photos saved in my computer with file names in First name_Middle Name_Last Name format. I would like to change it to Last Name, First Name, Middle Name.

For example:

From: One_Two_Three

To: Three, One, Two

I did a little research but I only found a replace-like method, but not rearranging the words.

CodePudding user response:

Use the -replace regex operator:

PS ~> 'One_Two_Three' -replace '([^_] )_([^_] )_([^_] )', '$3, $1, $2'
Three, One, Two

The pattern ([^_] ) will capture any sequence of non-_, and we can then "rearrange" each capture in the substitution pattern $3, $1, $2 ($1 refers to the group that captures One before the first _, etc.).

For renaming files, you'll want to reference the BaseName property on each file object:

Get-ChildItem path\to\folder\with\pictures -File -Filter *_*_*.* |Rename-Item -NewName {($_.BaseName -replace '([^_] )_([^_] )_([^_] )', '$3, $1, $2')   $_.Extension}

CodePudding user response:

Another method:

PS /tmp> Get-ChildItem -File -Filter *_*_*.* |
  Rename-Item -WhatIf -NewName {
    $w = $_.BaseName -split '_'; (($w[2], $w[0], $w[1]) -join ', ')   $_.Extension }

Output:

What if: Performing the operation "Rename File" on target "Item: /tmp/One_Two_Three.jpg Destination: /tmp/Three, One, Two.jpg".

Remove -WhatIf to do real renaming

  • Related