Rename file by similar file

February 25, 2010 at 06:45:58
Specs: Windows 7
I'm trying to write a script that renames a file if there's another filename with a different extension that shares the same prefix.

For example, if the file in question is named "01.png", it looks to see if there are any other files that begin with "01" with extension txt. If there exists " photo.txt", rename "01.png" to " photo.png"

So basically to look for txt file matches, I'd run the batch like so: renamesimilar.bat 01.png txt

I realize there may be problems when there are more than 1 match, so for now I'd like it to just go with the first match.

See More: Rename file by similar file

Report •

February 25, 2010 at 09:01:46

@echo off & setlocal
set pre=%~n1
set ext2=%2
if exist %pre%*.%ext2% (
for /f "tokens=2 delims=." %%a in ('dir /b %pre%*.txt') do set xx=%%a
ren %pre%.png %pre%.%xx%.png

Report •

February 25, 2010 at 10:56:26
I think I worked out a simple method:

for %%a in (%~n1*.%2) do rename %1 %%~na%~x1

only problem is that if there are multiple matches, it'll keep trying to rename it. any way to stop that?

Report •

February 26, 2010 at 08:44:51
There must be ... but, while we tackle that issue, tell us how you want to solve the problem. So, if you have

01.a test.txt
01.txt more.txt

... and you have 01.png, HOW do you decide the correct name ? Or, do you throw an error (cannot determine name) ?

Report •

Related Solutions

Ask Question