简体   繁体   中英

I'd like to use a wildcard with the SET command in Windows Batch so I don't have to know exactly what is in the string in order to match it

I'd like to use a wildcard with the SET command in Windows Batch so I don't have to know exactly what is in the string in order to match it.

Is this possible?

If this has already been asked and answered I apologize, I searched for a good while, but could not find it.

A: Yes. But it is not as powerful as it should be.

But first, let's answer a question that you didn't ask (yet) because it is a natural follow-up question.

Q: Will the question mark match any single character in the batch string search and replace with SET?
A: No. It is a regular character, and will only match it'self.

The asterisk IS a wildcard and WILL match multiple characters, but will ONLY match everything from the very beginning of the string . Not in the middle, and not from the end.

Useful Searches:

*x  
*how are you?

The above two searches CAN be matched. The first will match everything up to and including the first "x
" it runs across. The second one will match everything up to and including the first "how are you?" it finds.

Legal, but Unuseful, searches:

x*
Hello*
One*Three

The above three searches can NEVER be matched. Oddly they are also legal, and will cause no errors.
One exception: Hello* and x* WILL match themselves, but only if they are the very beginning of the string. (Thanks Jeb!)

Two examples you can type or paste in at a command prompt:

REM A successful search and replace.
SET X=Hello my friend. How are you?
SET X=%X:*.=%
ECHO Output: "%X%"

Output: " How are you?"

REM Unexpected action causing an unsuccessful search and replace.
SET X=Hello my friend. How are you?
SET X=%X:.*=%
ECHO Output: "%X%"

Output: "Hello my friend. How are you?"

Logiclly, .* should match everthing from the period on, resulting in the string being truncated to "Hello my friend". But since the * only matches from the start of the string, the .* matches nothing, and so the string was left unchanged.

Extremely old, but useful

As an executable set-ast

set string=abc*def*ghi
set-ast string "-dash-"
  :: -> "abc-dash-def-dash-ghi"

Where the arguments are given as set-ast <variable-name> <replacement-string>


replace * with -dash- (one time only)

Note: delayed expansion must be enabled

set string=abc*def
  :: -> "abc*def"
set right=%string:**=%
  :: -> "def"
set left=!string:%right%=!
  :: -> "abc*"
set left=%left:~0,-1%
  :: -> "abc"

set new-string=%left%-dash-%right%
  :: -> "abc-dash-def"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM