Removing *'s (asterisk) from variables?

Microsoft Windows
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Contact:

Removing *'s (asterisk) from variables?

Post by MigrationUser »

17 May 2007 09:55
NDog

Code: Select all

@echo off
setlocal enabledelayedexpansion

for /f "usebackq delims==$|<> tokens=1-6" %%g in ("%tempf%") do (
    if /i "%%h" equ "option value" ( 
        if not "%%l" equ "" (
            set country=%%l
            )
        )

    )
You will firstly notice bluesxmans style which i am utilising here,

However I am trying to remove * characters from this

so if %%l = UK*
how would I set country=UK

set country=!country:*=! ??
set country=!country:^*=! ??

those didnt work

cmd, vbs, ps, bash
autoit, python, swift

----------------------------

#2 18 May 2007 11:48
bluesxman

Yeah the asterisk is a complete arse pain.

For the example you give, I'd probably do this:

Code: Select all

for /f "tokens=1 delims=*" %%Z in ("%%~l") do set country=%%Z
See this thread for more in depth help on removing the asterisk.

BTW ... side issue, but why not do

if "%%l" NEQ ""

... same effect as "NOT ... EQU", but reads a little better (IMHO).

cmd | *sh | ruby | chef

----------------------------

#3 19 May 2007 00:17
NDog

Thanks again bluesxman! Well I see the logic in running another for /f loop on the variable, that makes sense now. And I'm always learning new tricks like using NEQ rather than if not. Thanks!

cmd, vbs, ps, bash
autoit, python, swift

----------------------------

#4 15 May 2020 13:38
zled55it

Following a code to replace wildcard * with [x] and ? with [q]

Code: Select all

@echo off
cls
goto :codeInit
+----------------------------------------------------------------------------------------------+
| decodifica dei parametri di ingresso sostituendo i caratteri wildcard usati per l'espansione |
| dei nomi di file:                                                                            |
| - * 0 o più caratteri qualsiasi (sostituito con [x] in analogia con * operatore mat. prod.)  |
| - ? un carattere qualsiasi      (sostituito con [q] question mark)                           |
|                                                                                              |
+----------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------+
|Cosa ho imparato:                                                                             |
| L'istruzione "if" richiede che i due operandi dell'espressione di confronto non contengano   |
| caratteri di separazione [,;=<space><tab>] della shell (interprete dei comandi cmd.exe).     |
| Se gli operandi contengono riferimenti a variabili da espandere allora il risultato          |
| dell'espansione deve essere privo di separatori. Quindi possiamo utilizzare separatori solo  |
| se servono nella prima fase di parsing ed espansione delle variabili. Nella successiva fase  |
| di parsing del comando "if", tali separatori non sono ammessi almeno che non siano preceduti |
| dal carattede ri escape [^] oppure si racchiuda l'operando dra virgolette ["], in analogia   |
| a quando si inserisce un parametro di riga di comando contenente spazi. Il caso pratico è    |
| l'inserimento di un pathname contenente spazi.                                               |
|                                                                                              |
| Il carattere speciale [*] non può essere sostituito direttamente in una stringa, vale a dire |
| che %var:*=abc% non funziona. Questo perchè * è considerato come wildcard in fase di         |
| espansione della espressione di sostituzione stringa:                                        |
| se var=ab*d allora %var:**=_%vale _d (ricerca della stringa che termina per * e sostituzione |
|                                      della stessa con [_]).                                  |
| Si è perciò utilizzato un for che opera su stringa suddividendola in sottostringhe con       |
| separator [*].                                                                               |
|                                                                                              |
| Il for esegue un solo ciclo isolando la prima sottostringa e la succseeiva restante stringa  |
| dopo il primo separatore [*] trovato.                                                        |
| (vedi https://ss64.org/viewtopic.php?id=200 "Removing *'s from variables?")                  |
|                                                                                              |
| Ho eliminato il primo ed ultimo * che avrebbero provocato eccezioni nel for                  |
+----------------------------------------------------------------------------------------------+
:codeInit

echo ------------ test loop
setlocal enableextensions enabledelayedexpansion
set "aStr[0]=a b "c d" ghi"
set "aStr[1]=a?b* cd*ef ghi"
set "aStr[2]=? * *.* *."
set "aStr[3]=a?b* cd*ef g? hi"
set "aStr[4]=a?b* cd*ef g? hi*"
set "aStr[5]=*a?b* cd*ef g? hi*"
set "aStr[6]=* *a?b* cd*ef g? hi* *"
set "aStr[7]=**a?b* cd*ef g? hi* *"
set "aStr[8]="*a ?b*" cd*ef g? hi"
set "aStr[9]="c:\Program Files\Common Files\microsoft shared\MSInfo\*.*",dir "^|test^|""
for /L %%A in (0,1,9) do (
	echo test %%A:
	call :doTest !aStr[%%A]!
)
echo ------------ end test loop
echo.
echo ------------ test from command line pars.
set "str=%*"
if "%str%" neq "" call :doTest !str!
echo ------------ end test from command line pars.
exit /b

:doTest str
setlocal enableextensions enabledelayedexpansion
	set str=%*
	:: -- value before encoding 
	echo initial: str=!str!

	:: -- value after encoding 
	call :encodeWildCardsDebug str
	echo encoded: str=!str!

	:: -- value after decoding 
	call :decodeWildCards str
	echo decoded: str=!str!
endlocal	
exit /b

:encodeWildCardsDebug str -- encode  parameters wildcard character "*" with "[x]" and "?" with "[q]" 
::                        -- str [input]    parameters string 
::                        -- str [output]   encoded parameters string 
setlocal enableextensions enabledelayedexpansion
	set str=!%1!
	if "!str:~0,1!" equ "*" set str=[x]!str:~1!
	if "!str:~-1,1!" equ "*" set str=!str:~0,-1![x]
	echo encodeWildCards: (before loop) str={!str!}
	:replaceStarDebug
		for /f "tokens=1* delims=*" %%A in ("!str!") do (
			echo encodeWildCards: ^(for cycle  ^) initial str={!str!}, var A={%%A}, var B={%%B}
			set "str=%%A"
			if [%%B] neq [] set "str=!str![x]%%B"
		)
		echo encodeWildCards: (after for  ) !str!
		if "!str:**=!" neq "!str!" goto replaceStarDebug
	set str=!str:?=[q]!
endlocal & set %1=%str%
exit /b

:encodeWildCards str -- encode  parameters wildcard character "*" with "[x]" and "?" with "[q]" 
::                   -- str [input]    parameters string 
::                   -- str [output]   encoded parameters string 
setlocal enableextensions enabledelayedexpansion
	set str=!%1!
	if "!str:~0,1!" equ "*" set str=[x]!str:~1!
	if "!str:~-1,1!" equ "*" set str=!str:~0,-1![x]
	:replaceStar
		for /f "tokens=1* delims=*" %%A in ("!str!") do (
			set "str=%%A"
			if [%%B] neq [] set "str=!str![x]%%B"
		)
		if "!str:**=!" neq "!str!" goto replaceStar
	set str=!str:?=[q]!
endlocal & set %1=%str%
exit /b

:decodeWildCards str -- decode 
::                   -- str [input]    parameters string 
::                   -- str [output]   encoded parameters string 
setlocal enableextensions enabledelayedexpansion
	set str=!%1!
	set str=!str:[x]=*!
	set str=!str:[q]=?!
endlocal & set %1=%str%
----------------------------

#5 15 May 2020 14:45
zled55it



**** same post with english translated comments ***

Code: Select all

@echo off
cls
goto :codeInit
+ -----------------------------------------------------------------------------------------------+ 
| decoding of input parameters by replacing wildcard characters used for file names expansion:   |
| - * 0 or more any characters (replaced with [x] in analogy with * operator mat. Prod.)         | 
| - ?  any character (replaced with [q] question mark)                                           |
|                                                                                                | 
+ -----------------------------------------------------------------------------------------------+ 
+ ----------------------------------------------------- -----------------------------------------+ 
| What I learned:                                                                                | 
| The "if" statement requires that the two comparison expression operands do not contains        | 
| shell separator characters [,; = <space> <tab>] (cmd.exe command interpreter).                 | 
| If the operands contain references to variables to be expanded then the expansion resulting    | 
| string must be free of separators. So we can use separators only if they are used in the       |
| first phase of parsing and variables expansion.                                                |
| In the next "if" command parsing phase, these separators are not allowed unless they           |
| are preceded by [^] escape char. Alternatively the entire operator must be between             |
| quotation marks ["] in analogy with a command line parameter string containing spaces.         |
|                                                                                                |
| The special character * cannot be replaced directly in a string. %var:*=abc% does not work.    |
| This is because * is considered as wildcard in the expansion phase of string replacement       |
| expression.                                                                                    | 
| If var=ab*d then %var:**=_% is _d (search for string ending in * and replace it with _).       | 
| Therefore i also used a for that operates on a string dividing it into substrings with         |
| separator  * , according to previous examples.                                                 | 
|                                                                                                | 
| The for executes a single loop isolating the first substring and the remaining string          |
| after the first separator  *  found.                                                           | 
|                                                                                                | 
| I eliminated the first and last * that would have caused exceptions in the for statement.      | 
+ ------------------------------------------------- ---------------------------------------------+
:codeInit

echo ------------ test loop
setlocal enableextensions enabledelayedexpansion
set "aStr[0]=a b "c d" ghi"
set "aStr[1]=a?b* cd*ef ghi"
set "aStr[2]=? * *.* *."
set "aStr[3]=a?b* cd*ef g? hi"
set "aStr[4]=a?b* cd*ef g? hi*"
set "aStr[5]=*a?b* cd*ef g? hi*"
set "aStr[6]=* *a?b* cd*ef g? hi* *"
set "aStr[7]=**a?b* cd*ef g? hi* *"
set "aStr[8]="*a ?b*" cd*ef g? hi"
set "aStr[9]="c:\Program Files\Common Files\microsoft shared\MSInfo\*.*",dir "^|test^|""
for /L %%A in (0,1,9) do (
	echo test %%A:
	call :doTest !aStr[%%A]!
)
echo ------------ end test loop
echo.
echo ------------ test from command line pars.
set "str=%*"
if "%str%" neq "" call :doTest !str!
echo ------------ end test from command line pars.
exit /b

:doTest str
setlocal enableextensions enabledelayedexpansion
	set str=%*
	:: -- value before encoding 
	echo initial: str=!str!

	:: -- value after encoding 
	call :encodeWildCardsDebug str
	echo encoded: str=!str!

	:: -- value after decoding 
	call :decodeWildCards str
	echo decoded: str=!str!
endlocal	
exit /b

:encodeWildCardsDebug str -- encode  parameters wildcard character "*" with "[x]" and "?" with "[q]" 
::                        -- str [input]    parameters string 
::                        -- str [output]   encoded parameters string 
setlocal enableextensions enabledelayedexpansion
	set str=!%1!
	if "!str:~0,1!" equ "*" set str=[x]!str:~1!
	if "!str:~-1,1!" equ "*" set str=!str:~0,-1![x]
	echo encodeWildCards: (before loop) str={!str!}
	:replaceStarDebug
		for /f "tokens=1* delims=*" %%A in ("!str!") do (
			echo encodeWildCards: ^(for cycle  ^) initial str={!str!}, var A={%%A}, var B={%%B}
			set "str=%%A"
			if [%%B] neq [] set "str=!str![x]%%B"
		)
		echo encodeWildCards: (after for  ) !str!
		if "!str:**=!" neq "!str!" goto replaceStarDebug
	set str=!str:?=[q]!
endlocal & set %1=%str%
exit /b

:encodeWildCards str -- encode  parameters wildcard character "*" with "[x]" and "?" with "[q]" 
::                   -- str [input]    parameters string 
::                   -- str [output]   encoded parameters string 
setlocal enableextensions enabledelayedexpansion
	set str=!%1!
	if "!str:~0,1!" equ "*" set str=[x]!str:~1!
	if "!str:~-1,1!" equ "*" set str=!str:~0,-1![x]
	:replaceStar
		for /f "tokens=1* delims=*" %%A in ("!str!") do (
			set "str=%%A"
			if [%%B] neq [] set "str=!str![x]%%B"
		)
		if "!str:**=!" neq "!str!" goto replaceStar
	set str=!str:?=[q]!
endlocal & set %1=%str%
exit /b

:decodeWildCards str -- decode 
::                   -- str [input]    parameters string 
::                   -- str [output]   encoded parameters string 
setlocal enableextensions enabledelayedexpansion
	set str=!%1!
	set str=!str:[x]=*!
	set str=!str:[q]=?!
endlocal & set %1=%str%
Post Reply