Batch renaming files

elgin229 used Ask the Experts™
Hello everyone,
In Windows 10. . . I need to remove the first 4 characters from about 250 file names.  They look like this: [ 005_this is a squirrel.jpg ].  I want it to read [ this is a squirrel.jpg ]

I can use CMD and I'm just starting with Powershell.

Thanks so much in advance.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Bill PrewIT / Software Engineering Consultant
Top Expert 2016

Here's a small BAT script that you could try to get the job done.  It assumes all the JPG files in the current folder need to be renamed.  Save the BAT, CD to the folder with the files, and run the BAT.  It's in test mode, and will just echo the REN commands it would execute to the command console.  If you like what that look like remove the ECHO on the REN line and run for real.

@echo off
setlocal EnableDelayedExpansion

for %%A in ("%.jpg") do (
    set name=%%~nxA
    set name=!name:~4!
    ECHO ren "%%~A" "!name!"

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018
PowerShell; this will only rename .jpg files that actually start with digits, followed by an underscore. It's in test mode and will only display what it would do; remove the -WhatIf at the end to run it for real.
It first gets all jpg files in the directory specified, then excludes all items where the name does not start with digits and an underscore, then renames to the part after the underscore.
The -NewName argument for Rename-Item is in this case a scriptblock where the new name will be constructed dynamically from the element passed in the pipeline ($_).
The short version, how you might enter it in a PS prompt, using aliases:
gci C:\Temp *.jpg | ? {$_.Name -match '^\d+_'} | ren -new {"$($_.BaseName.Split('_', 2)[1])$($_.Extension)"} -WhatIf

Open in new window

In a script, though, aliases should be avoided, and named arguments should be used, so here's the full version:
GetChildItem -Path C:\temp -Filter *.jpg | Where-Object {$_.Name -match '^\d+_'} | Rename-Item -NewName {"$($_.BaseName.Split('_', 2)[1])$($_.Extension)"} -WhatIf

Open in new window

Mike SunSenior Systems Engineer (IBM - retired)

There are also some small 3rd party tools as an alternative such as Lupus Rename


I really appreciate these responses.  Because of my limited knowledge, I was able to get the answer from oBdA to work so I'm grateful for that, but also appreciative for the other responses.

I downloaded and installed the Lupus Rename program and was able to get the files renamed, but couldn't figure out how to actually save the changes.  I'm sure it's simple.

Nevertheless, I got the files renamed and I'm happy,

Thank you, gentlemen, for your assistance.


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial