Search code examples
javascriptbatch-filedosfilenames

javascript - change filename


I would like to use JavaScript or a DOS script to add some words before and after the original filename. Have you any script I can use?

ORIGINAL:

AAAA.pdf  
BBBB.pdf  
CCCC.pdf  
CCCC_01.pdf  
CCCC_02.pdf  
CCCC_03.pdf  
CCCC_04.pdf  
DDDD.pdf  
EEEE.pdf  

Target:

999_AAAA_333.pdf  
999_BBBB_333.pdf  
999_CCCC_333.pdf  
999_CCCC_333_01.pdf  
999_CCCC_333_02.pdf  
999_CCCC_333_03.pdf  
999_CCCC_333_04.pdf  
999_DDDD_333.pdf  
999_EEEE_333.pdf

Solution

  • Assuming that the letters are always 4 digits long, you can do this, which will insert the 999_ at the front, and the _333 right after the the 4 digits of letters:

    @echo off
    
    setlocal ENABLEDELAYEDEXPANSION
    
    cd /d c:\folder\with\pdf\files
    
    for /f "delims=" %%i in ('dir *.pdf /b') do (
      set fn=%%i
      ren %%i 999_!fn:~0,4!_333!fn:~4,-3!.pdx
    )
    
    ren *.pdx *.pdf
    
    endlocal
    

    The ren in the for loop intentionally renames the .pdf files to .pdx so that the for loop won't pick up the renamed files again and perform the rename a second time. Then all the .pdx files are renamed to .pdf...