BAT command to insert a char. in a file name

December 2016




Issue


I have a problem, one whose solution I stumbled onto a couple years ago but - alas - my storage recently crashed and I lost the batch file!

We start w/ this awkward file name:
rank(all)_so2_1hr_conc_A_2p5h10.dat
The following BAT utility cleverly strips everything in front of the 'A' (first 23 chars.):

@echo off 
for %%i in (*.dat) do (set fName=%%i) & call :rename 
goto :eof 
:rename 
:: Crops the 1st 23 characters of fName ('rank(all)_so2_1hr_conc_'): 
ren %fName% %fName:~23% 
goto :eof 


Great! This renders:

A_2p5h10.dat

Now I need to convert this to:

A_2p5h100.dat

Notice '...h10' needs to be '...h100'. Note that, while in this example, the part preceding the '.' is 'A_2p5h10', it could be any 8-character string (so we'll need a wildcard or something).

Can you please suggest a routine that will add the ' 0 ' in the middle of the file name (preceding the '.')? There are hundreds of file names in the directory that need to have this conversion.

As I recall, the critical command (I believe used REN) that used to do this was extremely simple (contained one of more %, as I recall).

Solution


You can use this script:
@echo off 
for %%i in (*.dat) do (set fName=%%i) & call :rename 
goto :eof 
:rename 
:: Rename the file by discarding first 23 chars, and last 7 and adding H100.plt at the end 
ren %fName% %fName:~23,-7%H100.plt 
goto :eof 

Note


Thanks to Tommy for this tip on the forum.

Related :

This document entitled « BAT command to insert a char. in a file name » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.