How to bring a special string into a variable?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Furplado
Posts: 12
Joined: 13 Feb 2021 10:18

How to bring a special string into a variable?

#1 Post by Furplado » 18 Feb 2021 11:19

I have all done in a cmd-window:

I want to have a variable with the following content:

Code: Select all

%BUFFER:*Word=%

This is what I have tried out:

Code: Select all

C:\Users\D>set "a=%BUFFER:*Word=%"
This is now the content of the variable a

Code: Select all

C:\Users\D>echo "%a%"
".Document.12"

C:\Users\D>
My expectation was, that the content would be

Code: Select all

%BUFFER:*Word=%
Question:
How can I bring "%BUFFER:*Word=%" into variable a?


Thank you.

Squashman
Expert
Posts: 4470
Joined: 23 Dec 2011 13:59

Re: How to bring a special string into a variable?

#2 Post by Squashman » 18 Feb 2021 13:24

If you want literal % symbols to be assigned to a variable in a batch file then you need to double them.

Code: Select all

set "a=%%BUFFER:*Word=%%"
At the command prompt just use the normal ^ to escape the %.

Furplado
Posts: 12
Joined: 13 Feb 2021 10:18

Re: How to bring a special string into a variable?

#3 Post by Furplado » 18 Feb 2021 14:10

Thank you.

Very strange.
I have exactly repeated what I have done in post 1. And now the behaviour is different (without using "^" ):

Code: Select all

C:\Users\D>set "a=%BUFFER:*Word=%"

C:\Users\D>echo "%a%"
"%BUFFER:*Word=%"

C:\Users\D>

Squashman
Expert
Posts: 4470
Joined: 23 Dec 2011 13:59

Re: How to bring a special string into a variable?

#4 Post by Squashman » 18 Feb 2021 14:28

Furplado wrote:
18 Feb 2021 14:10
Thank you.

Very strange.
I have exactly repeated what I have done in post 1. And now the behaviour is different (without using "^" ):

Code: Select all

C:\Users\D>set "a=%BUFFER:*Word=%"

C:\Users\D>echo "%a%"
"%BUFFER:*Word=%"

C:\Users\D>
If you previously defined the variable BUFFER in the existing environment it will expand the variable. If it is not defined then it will just assign the literal string to the variable.

Code: Select all

H:\>set "buffer="

H:\>set "a=%BUFFER:*Word=%"

H:\>echo %a%
%BUFFER:*Word=%

H:\>set "buffer=word.document"

H:\>set a=%^BUFFER:*Word=%

H:\>echo %a%
%BUFFER:*Word=%

H:\>set a=%BUFFER:*Word=%

H:\>echo %a%
.document

Furplado
Posts: 12
Joined: 13 Feb 2021 10:18

Re: How to bring a special string into a variable?

#5 Post by Furplado » 18 Feb 2021 14:53

OK. I see "^" must be before a variable.

Post Reply