I have the following string
set str=aaaaa,bbbbb,ccccc,dddd
I need to replace everything from the first ,
(comma) till the end of string. but I don't know how the string starts.
I can't use the * wildcard as it is not in the start of string, so something like that -
set str=%str:,*=% >>>> Will not work
Any ideas ? it must be in a batch script
There is a very simple and fast solution that avoids a FOR loop: use search and replace to inject a concatenated REM command at each comma :-)
@echo off
set str=aaaaa,bbbbb,ccccc,dddd
set "str=%str:,="&rem %
echo str=%str%
Explanation
Here is the the important line of code, before any expansion takes place:
set "str=%str:,="&rem %
And here is what the line is transformed into after variable expansion:
set "str=aaaaa"&rem bbbbb"&rem ccccc"&rem dddd
It becomes a SET statement, followed by a REM statement. The &
operator allows you to combine multiple commands on one line. There is only one REM statement because everything after the first REM is considered part of the remark.
To remove everything after the first comma you can use
@echo off
setlocal enabledelayedexpansion
set str=aaaaa,bbbbb,ccccc,dddd
for /f "delims=," %%a in ("%str%") do (
set str=%%a
echo !str!
)
pause >nul
To replace, simply strip it and append the new string on the end
set str=%%a,new,string
Update
This will do the same, but without a for
loop
@echo off
setlocal enabledelayedexpansion
set str=aaaaa,bbbbb,ccccc,dddd
set strip=%str%
set length=0
set start=0
set new=
:loop
if defined strip (
set strip=!strip:~1!
set /a length+=1
goto :loop
)
:comma
if %length% gtr 0 (
call :add !start!
if "!char!"=="," (
goto :break
) else (
set new=!new!!char!
set /a length-=1
set /a start+=1
goto comma
)
)
:break
echo %new%
pause >nul
:add
set char=!str:~%1,1!