Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch * wildcard replacement

I have a string base of the form *+*. I want to get everything before the +. For example, if base=foo+bar, I want to get foo.

I've tried doing it with string replacement

set left=%base:+*=%

But this results in left storing foo+bar.

Interestingly, string replacement works for getting everything right of the +:

set right=%base:*+=%

Is +* being replaced by + (i.e. the wildcard is substituting for 0 characters)? Is there a better way to accomplish my task?

EDIT: I'm actually doing this in a for loop. Therefore, delayed expansion is on and (I think) I need to use !. Full code here:

for /d %%d in (*+*) do (
    set base=%%d
    set right=!base:*+=!
    set left=!base:+*=! ::this part doesn't work
    if !left:~-2!==!right:~-2! ( ::do only if last 2 chars match
        copy %%d mirrors
        copy %%d\%%d_montage.bmp mirrors
    )
)

EDIT 2: Comments in code above are only for readability here on SO. ::-style comments may not work correctly in for loops.

like image 241
LastStar007 Avatar asked Mar 15 '23 09:03

LastStar007


2 Answers

You may use this trick:

@echo off

set "base=foo+bar"

set "left=%base:+=" & set "right=%"

echo Left=%left%
echo Right=%right%

EDIT: If you want to use the method inside a for loop, use it this way:

@echo off
setlocal EnableDelayedExpansion

for %%a in ("one+two" "first+last") do (
   call :separate %%a
   echo Left=!left!
   echo Right=!right!
   echo/
)
goto :EOF

:separate
set "base=%~1"
set "left=%base:+=" & set "right=%"
exit /B
like image 61
Aacini Avatar answered Mar 23 '23 08:03

Aacini


I've never had much luck with environment variable string replacement with wildcards, probably because of the right issue wOxxOm notes.

I'd tend to favor this method here:

for /f "tokens=1,2 delims=+" %a in ('echo %base%') do (
    set left=%a
    set right=%b
)
like image 30
Bacon Bits Avatar answered Mar 23 '23 07:03

Bacon Bits