Nena
Nena

Reputation: 13

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

Upvotes: 0

Views: 681

Answers (3)

ScriptKidd
ScriptKidd

Reputation: 841

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:

Upvotes: 0

Nena
Nena

Reputation: 13

In the end I used Alex's suggestion, but figured out how to put it in a .bat script:

@echo off
setlocal ENABLEDELAYEDEXPANSION

cd /D %1

for %%F in (*.nc) do (
  set oldName=%%F
  set newName=!oldName:~0,44!!oldName:~60!
  rename !oldName! !newName!
)

Note: %1 is a path to the folder with files to be renamed (on the D: drive), provided as an argument to the .bat file in the command line.

What was important was to not have a space when defining variables! (e.g. oldName = %%F did not work but oldName=%%F did work)

Upvotes: 1

Alex Sveshnikov
Alex Sveshnikov

Reputation: 4329

Use the substring syntax %name:~start,length%:

> set name=S2A_MSIL2A_20200322T184031_N0214_R070_T12VVJ_20200322T231131_A03.nc
> echo %name%
S2A_MSIL2A_20200322T184031_N0214_R070_T12VVJ_20200322T231131_A03.nc
> echo %name:~0,44%%name:~60%
S2A_MSIL2A_20200322T184031_N0214_R070_T12VVJ_A03.nc

Upvotes: 0

Related Questions