Page 1 of 1
How to bring a special string into a variable?
Posted: 18 Feb 2021 11:19
by Furplado
I have all done in a cmd-window:
I want to have a variable with the following content:
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
Question:
How can I bring "%BUFFER:*Word=%" into variable a?
Thank you.
Re: How to bring a special string into a variable?
Posted: 18 Feb 2021 13:24
by Squashman
If you want literal % symbols to be assigned to a variable in a batch file then you need to double them.
At the command prompt just use the normal ^ to escape the %.
Re: How to bring a special string into a variable?
Posted: 18 Feb 2021 14:10
by Furplado
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>
Re: How to bring a special string into a variable?
Posted: 18 Feb 2021 14:28
by Squashman
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
Re: How to bring a special string into a variable?
Posted: 18 Feb 2021 14:53
by Furplado
OK. I see "^" must be before a variable.