Search code examples
regexbatch-filebatch-processingbatch-rename

Remove piece of filename in .bat file


I'm trying to rename a bunch of files in a folder using a .bat script.

Original filename: S2A_MSIL2A_20200322T184031_N0214_R070_T11UPA_20200322T225116_A03.nc

The bold part (second date/time) is what I'm trying to remove

Goal filename: S2A_MSIL2A_20200322T184031_N0214_R070_T11UPA_A03.nc

I've tried this:

rename "S??_??????_???????????????_?????_????_??????_???????????????_???.nc" "S??_??????_???????????????_?????_????_??????_???.nc"

The different sections of the file should always have the same number of characters, and all files start with S and end in .nc

...but it doesn't seem to work properly. Sometimes files don't get renamed, and sometimes the get renamed, but incorrectly. Can anyone help? I've done many searches on stackexchange to try and figure this out, but none of the other solutions seem to work -- what regex do I need for this?

Here are some other examples of files to be renamed: S2A_MSIL2A_20200322T184031_N0214_R070_T12VVJ_20200322T231131_A03.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VVK_20200322T231131_A01.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VVK_20200322T231131_A02.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VVK_20200322T231131_A03.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VWK_20200322T231131_A01.nc

should become:

S2A_MSIL2A_20200322T184031_N0214_R070_T12VVJ_A03.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VVK_A01.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VVK_A02.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VVK_A03.nc S2A_MSIL2A_20200322T184031_N0214_R070_T12VWK_A01.nc


Solution

  • An alternative solution using FOR /F:

    @echo off
    FOR %%F in (*.nc) do ( 
    FOR /F "tokens=1-8 delims=_" %%a in ("%%~nF") do ren "%%F" "%%a_%%b_%%c_%%d_%%e_%%f_%%h.nc"
    )
    

    Screenie: