Search code examples
batch-filebatch-rename

How to insert a text in front of the filenames using a batch script


@echo off 
for %%a in (*.xhtml) do (

ren "%%~fa" "epub_%%~nxa"
)

I am using the code for insert a text ("epub_") to all the file names.

The file name is

00_Cover_Page.xhtml
01_Halftitle.xhtml
02_Title.xhtml
03_Copyright.xhtml
04_Dedication.xhtml
05_Preface.xhtml
06_Contents.xhtml

It's renaming good except "00_Cover_Page.xhtml"

epub_epub_00_Cover_Page.xhtml ("epub_" Inserted twice in the filename only)

epub_01_Halftitle.xhtml
epub_02_Title.xhtml
epub_03_Copyright.xhtml
epub_04_Dedication.xhtml
epub_05_Preface.xhtml
epub_06_Contents.xhtml

How could it be happened?


Solution

  • As pointed out in MC ND's comment, an explanation of the behavior is available at https://stackoverflow.com/a/19705611/1012053. The FOR loop buffers only a portion of the directory, and when it goes back to disk to read additional file entries, it can pick up already renamed files.

    jeb's answer on that same question explains how to avoid the problem by using a FOR /F loop processing a DIR /B command - the output of the DIR /B command is captured in its entirety before iterations begin.

    @echo off
    for /f "eol=: delims=" %%F in ('dir /b /a-d *.xhtml') do ren "%%F" "epub_%%~nxa"
    

    An alternative is to use my JREN.BAT regular expression renaming utility. JREN.BAT is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward.

    jren "^" "epub_" /fm *.xhtml
    

    Use CALL JREN if you put the command within a batch script.