Separate batch string, remove substr

Viewed 31

I have the following string:

9/14/22 11:00:12,,,0,0,,,,,,

I need to remove 9/14/22 11:00:12 so I only have ,,,0,0,,,,,, left over.

@echo off
set str=9/14/22 11:00:12,,,0,0,,,,,,
FOR /F "tokens=1* delims=," %%a in ("%str%") DO (
    set REMOVE_STR=%%a
)
set REMAINING_STR=%str:;%REMOVE_STR%;=%
echo New string: %REMAINING_STR%

The output is just the original string, so I know there's a problem with the substr removal step. But, I can't figure out what I'm doing wrong.

2 Answers

You don't need a for loop, or delayed expansion for that task, you can do it with direct variable expansion and sustitution, just like this:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "str=9/14/22 11:00:12,,,0,0,,,,,,"

Set "REMAINING_STR=,%str:*,=%
Echo New string: %REMAINING_STR%

The above substitutes everything up to, and including, the first comma, with nothing, in the expanded variable, and precedes that with the initially first removed comma.

You could alternatively substitute everything up to, and including, the first comma, with a comma, like this:

Set "REMAINING_STR=%str:*,=,%

You need delayed expansion to use variables inside a code block that you defined/changed within the same block:

@echo off
setlocal enabledelayedexpansion 

set str=9/14/22 11:00:12,,,0,0,,,,,,
FOR /F "tokens=1 delims=," %%a in ("%str%") DO ( 
  set "remaining_str=!str:%%a=!"
  echo New string: !Remaining_Str!
)

Output:

New string: ,,,0,0,,,,,,
Related