Home > Software engineering >  Batch script - How to replace characters before a delimiter
Batch script - How to replace characters before a delimiter

Time:06-15

I'm new in batch scripting and a lot of things are still not 100% understandable for me.

I've found some sources (Source1, Source2) about substrings but I still can't figure how to replace characters before a delimiter.

I have files called like this :

File 1 : rem1020aa_10.zip
File 2 : com12909aa_32.zip
File 3 : fig129439aa_324.zip

As you can see my strings can have different lengths. All I want to do is replace the "aa" with something else.

Update - Sorry forgot to mention that I want to replace before the _ delimiter.

For exemple : rem1020duh_10.zip

Watch my current code :

@echo off
setlocal enableDelayedExpansion
set arg1=%1
for /f "delims=" %%b in ('dir /b /s /a-d "C:\Test"') do (
  set "arg1=%%~nxc" 
  echo !arg1:~-6,2!
)

The result I get :

09
43
0a

I know that it will not work in that case because the lengths are different, but it's one method between multiple I tried.

I tried the first answer from Source2 too but still I can't find a way to do that.

CodePudding user response:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "sourcedir=u:\your files"
SET "replaceme=aa"
SET "replacement=duh"

FOR /f "delims=" %%b IN ('dir /b /a-d "%sourcedir%\*" ') DO (
 ECHO found filename "%%b"
 rem store name part before "_" in `fileprefix
 FOR /f "tokens=1*delims=_" %%q IN ("%%~nb") DO (
  ECHO q=%%q r=%%r
  SET "fileprefix=%%q"
  rem is the 2-character string at the end of fileprefix "aa"? - note: /i means case-insensitive
  IF /i "!fileprefix:~-2!"=="%replaceme%" (
   ECHO %%q ends %replaceme%
   ECHO so new name is !fileprefix!, except the last 2 characters   replacement   _   %%r
   ECHO and extension is %%~xb
   ECHO REN "%%b" "!fileprefix:~0,-2!%replacement%_%%r%%~xb"
  )
 )
 ECHO ----------------------
)

GOTO :EOF

This should demonstrate how I might approach this problem. The steps are echoed - obviously, those echoes could be deleted once the method is understood.

Note that it would also be possible to use "%sourcedir%\*%replaceme%_*" as the filemask which would reduce the incidence of filenames detected that do not fit the criteria required.

  • Related