Home > Software design >  Trim a GUID in batch script
Trim a GUID in batch script

Time:01-08

I have a string

<?define customGUID=             "DA7C36F0-A749-4CC5-9575-398C06039325"?>

I am trying to trim out DA7C36F0-A749-4CC5-9575-398C06039325 from this line.

To begin with i am trying to set this string in a variable but i am not able to do that may be because of < and ? in string, I tried:

set "var=<?define customGUID=            "DA7C36F0-A749-4CC5-9575-398C06039325"?>"

But later i was able to fetch the string somehow at runtime and now i have the variable

line=<?define customGUID=            "DA7C36F0-A749-4CC5-9575-398C06039325"?>

I am not able to figure out how can i trim only value i.e DA7C36F0-A749-4CC5-9575-398C06039325 out of this variable using batch script.

I gave it a try to trim suffix atleast with:

set "line=%line:"?>%"

But getting error, can anyone help with better approach? Note: the spaces are included in string

CodePudding user response:

You can split the string using " as a delimiter, but since quotes are used to specify for loop options, the syntax looks a little different than usual:

@echo off
setlocal enabledelayedexpansion
set "line=<?define customGUID=            "DA7C36F0-A749-4CC5-9575-398C06039325"?>"
echo !line!

for /f tokens^=2^ delims^=^" %%A in ("!line!") do set "line=%%A"
echo !line!

CodePudding user response:

You may use this very simple trick:

@echo off
setlocal EnableDelayedExpansion

set "var=<?define customGUID=            "DA7C36F0-A749-4CC5-9575-398C06039325"?>"

set "i=0" & set "v0=%var:"=" & set /A i =1 & set "v!i!=%"

echo Desired string: [%v1%]

If you want to know how this works, remove the @echo off line and carefully review what appears in the screen...

CodePudding user response:

Your command line:

set "line=%line:"?>%"

does not make sense, because there is an =-sign missing (refer to sub-string substitution):

set "line=%line:"?>=%"

To trim away the unwanted prefix you could remove everything up to the first quotation mark:

set "line=%line:*"=%"

However, this only works when you do that after having removed the suffix, because you are dealing with unbalanced quotation marks, which are problematic together with immediate variable expansion. If you want to change the order, you have to implement escaping escaping in order not to exhibit the redirection operator > unquoted:

set ^"line=%line:*"=%"
set "line=%line:"?>=%"

To avoid the need of escaping depending on the input string, use delayed variable expansion, like this:

set "line=<?define customGUID=            "DA7C36F0-A749-4CC5-9575-398C06039325"?>"
set line
rem // First enable delayed expansion:
setlocal EnableDelayedExpansion
rem // Then apply it by replacing `%` with `!`:
set "line=!line:*"=!"
set "line=!line:"?>=!"
set line
rem // This restores the previous state:
endlocal
rem // At this point changes in the variable are no longer available due to localisation:
set line
  •  Tags:  
  • Related