Peter
Peter

Reputation: 3

Remove end of filename using PowerShell

Is possible to use PowerShell to remove end of filename of all files in folder? Examples:

So I want remove everything from "by" to ".jpg".

Upvotes: 0

Views: 4001

Answers (3)

Dave Sexton
Dave Sexton

Reputation: 11188

How about using a regex replace like so:

Get-ChildItem -Filter "*.jpg" | % {
    Rename-Item $_.FullName -NewName ($_.FullName -replace '_by_.*\.jpg$', '')
} 

If the regex doesn't find a match the file name is left unchanged.

Upvotes: 0

FoxDeploy
FoxDeploy

Reputation: 13537

I would do it using a ForEach loop, like so:

gci e:\temp\*.jpg | % {
Rename-Item -path $_.FullName -NewName "$($_.Name.Substring(0,$_.Name.LastIndexOf('by')))$($_.Extension)" -WhatIf }

What if: Performing the operation "Rename File" on target "Item: E:\temp\moira_by_kr0npr1nz-d8poqdb.jpg Destination: E:\temp\moira_.jpg".
What if: Performing the operation "Rename File" on target "Item: E:\temp\redemptionthe_hunters_by_danluvisiart-d8oy1ef.jpg Destination: E:\temp\redemptionthe_hunters_.jpg"
What if: Performing the operation "Rename File" on target "Item: E:\temp\shining_eyestep_by_step_by_ryky-d8pp6xh.jpg Destination: E:\temp\shining_eyestep_by_step_.jpg".

The logic is that we get a listing of the files that we want (all JPGs for instance), we then iterate through them using ForEach-Object, and specify the NewName parameter to change the name.

I'll break down what is happening inside of the quotes there:

  1. Take the Name and find the last time the word 'by' appears, which returns the numerical position inside of the string (the index)
  2. Use the SubString command to select everything from the beginning of the string to the above, everything from the beginning until the word 'by' appears for the last time.
  3. Grab the original extension of the file and make sure we append that to the end.

I tested this on a directory with a few files like this, and it worked like a charm. Run it once with -WhatIf, so you can see what would happen. If you like what you see, run it again without the -WhatIf.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

Yes, you could you use the LastIndexOf() method on the files BaseName to find out where to cut it off, then use Substring():

Set-Location C:\path\to\folder

Get-ChildItem -Path $PWD -Filter "*.jpg" |ForEach-Object {
    if(($lastIndex = $_.BaseName.LastIndexOf("_by_")) -ne -1){
        $NewName = "{0}{1}" -f $_.BaseName.Substring(0, $lastIndex),$_.Extension
        Rename-Item $_.FullName -NewName $NewName
    }
}

If LastIndexOf() can't find the substring we're looking for (in this case _by_), it returns -1, in which case nothing should be done

Upvotes: 1

Related Questions