简体   繁体   中英

batch file to find files with double file extensions and remove the last one

I have several folders that have files with double file extensions along with regular file extensions. I need to create a batch script to search all the folders and remove the last extension with any files that have double extensions. None of the file extensions are consistent.

Here's an example

C:\test\regular.exe
C:\test\picture.jpg.doc
C:\newtest\document.doc.pdf

End Result I need

C:\test\regular.exe
C:\test\picture.jpg
C:\newtest\document.doc

Try this and remove the echo , if the output is OK:

@echo off &setlocal
for /r \ %%i in (*) do (
    for %%j in ("%%~ni") do if "%%~xj" neq "" echo ren "%%~fi" "%%~nj"
)

Edit: added support for the entire HD.

@ECHO OFF
SETLOCAL

SET sourcedir=c:\sourcedir
FOR /r "%sourcedir%" %%i IN (*.*) DO (
 FOR %%n IN ("%%~ni") DO IF NOT "%%~xn"=="" IF NOT EXIST "%%~dpni" ECHO REN "%%~fi" "%%~ni"
 FOR %%n IN ("%%~ni") DO IF NOT "%%~xn"=="" IF EXIST "%%~dpni" ECHO CAN NOT REN "%%~fi" "%%~ni"
)

GOTO :EOF

This batch should accomplish the task.

For each file in the tree rooted at sourcedir , if the NAME of the file itself contains an 'extension' and the filename without the original extension does not exist, then rename the file. That way, if ...picture.jpg.doc is found, the rename should occur only if ...picture.jpg does not exist.

The command to rename is simply ECHO ed. You'd need to remove the ECHO keyword to activate the rename - after verifying that's what you want to do.

I've added a second line to report that a rename could not be done because of an existing file.. This could be done very slightly better, but it will work.


Revised to modify name in case simple rename can not be done.

Caution - this version will rename immediately - there are no ECHO es to provide a list first because it's nonsense to provide such a list when renaming a file may produce different results on the main rename run.

@ECHO OFF
SETLOCAL

SET sourcedir=c:\sourcedir
FOR /r "%sourcedir%" %%i IN (*.*) DO (
 FOR %%n IN ("%%~ni") DO IF NOT "%%~xn"=="" IF EXIST "%%~dpni" (
  SET renreq=Y
  FOR %%a IN (new alt extra another 1 2 3 4 5 6 7 8 9) DO IF DEFINED renreq (
   IF NOT EXIST "%%~dpi%%~nn_%%a%%~xn" (
    REN "%%~fi" "%%~nn_%%a%%~xn"
    SET "renreq="
   )
  )
  IF DEFINED renreq ECHO CAN NOT REN "%%~fi"
 ) ELSE (
 REN "%%~fi" "%%~ni"
 )
)

GOTO :EOF

Reasonably obviously, the list of "extras" can be extended if required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM