Batch - Get string between first and last double quotes - batch-file

I have a string like this:
Testing:"abc"def"ghi"
I want to get: abc"def"ghi and put it into a variable, is there any possible way?
I want a general way of doing that (first and last quotes, not first and fourth quotes)

This will work reliably as long as the string does not contain unquoted special characters like & | > < ^
#echo off
set str=Testing:"abc"def"ghi"extra
echo str = %str%
set "new=%str:*"=%
echo new = %new%
-- OUTPUT --
str = Testing:"abc"def"ghi"extra
new = abc"def"ghi
Explanation
There are two parts to this solution, both in the same line of code.
1) Remove all characters up through the first ".
This part uses the documented search and replace feature of variable expansion, with an asterisk before the search string. The following is an excerpt from the help gotten by typing HELP SET or SET /? from the command prompt.
Environment variable substitution has been enhanced as follows:
%PATH:str1=str2%
would expand the PATH environment variable, substituting each occurrence
of "str1" in the expanded result with "str2". "str2" can be the empty
string to effectively delete all occurrences of "str1" from the expanded
output. "str1" can begin with an asterisk, in which case it will match
everything from the beginning of the expanded output to the first
occurrence of the remaining portion of str1.
2) Find the last occurrence of " and truncate the string at that point.
The entire SET assignment expression can be enclosed in quotes, and the enclosing quotes will be discarded and all text after the last quote ignored. The statement below will define variable var to have a value of value.
set "var=value" this text after the last quote is ignored
If there is no last quote, then the entire remainder of the line is included in the value, possibly with hidden spaces.
set "var=This entire sentence is included in the value.
I am not aware of any official documentation for this feature, but it is an important tool for batch file development.
This process occurs after the expansion from part 1 has completed. So the the SET truncates at the last occurrence of " in the expanded value.

Related

Remove last char from batch variable

I have a batch variable called version with this value "2930.2323 "
Now i want to remove the last character (or all spaces). I've tried both ways but the whitespace is not removed.
// MYVAR is set at the beginning of my batch file by another source code
SET "MYVAR=%MYVAR: =%"
Your code doesn't remove "Whitespaces", but SPACEs only (ie if it's a TAB it won't be removed unless you add another line to remove TABs too).
For your given string, I suggest another approach:
for %%a in (%myvar%) do set "myvar=%%a"
echo --%myvar%--
Note: that only works for whitespaces at the beginning or end of the string. A space in the middle of the string will split the string into two (or more). Also, some special characters will be problematic. But it will work with strings like your example ("Version numbers")

Set variable to %%f [duplicate]

This question already has answers here:
Defining and using a variable in batch file
(4 answers)
Closed 4 years ago.
I set a variable in cmd with the set command, and tried to echo it.
Here is an example:
C:\Users\Logan>set var = text
C:\Users\Logan>set var
var = text
C:\Users\Logan>echo %var%
%var%
C:\Users\Logan>
Is there a way to force the cmd to echo the variable and not the raw text?
Assigning a value/string to an environment variable
It is best to use following syntax with command extensions enabled to define or modify an environment variable:
set "var=text"
The command is set and the parameter is "variable=value".
The parameter string can be enclosed in double quotes as on all commands as long as command extensions are enabled as by default.
If the double quotes are not used around variable=value, command set interprets everything to end of line after the first equal sign including not visible spaces and horizontal tabs at end of line as string value to assign to the variable.
The name of the variable starts with first non whitespace character (after double quote if used) and ends left to first equal sign. The value assigned to the variable starts right of first equal sign and ends at end of line or last double quote.
set VAR = TEXT
The command line above creates an environment variable with name VARSpace and assigns the string SpaceTEXT to this variable.
The usage of
set var="text"
is often not correct as this results in assigning to variable var the text with the quotes included and all trailing spaces and tabs. Referencing now var on another code line with surrounding quotes often results in an error message as the variable holds itself the text already with quotes. For more details see the answer on How to set environment variables with spaces?
Example:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "var=text"
set "var = text"
set "var1=and more text"
set var2="and more text"
set var3="text with 1 trailing space"
set var
echo var3=%var3%^<- Do you see the trailing space?
echo/
set UnwantedSpaceVar=Hello
echo %UnwantedSpaceVar%! ^<- Where does the space come from?
echo/
echo There is a trailing space after Hello in this code snippet.
echo/
set "TrailingSpacesIgnored=Hi"
echo %TrailingSpacesIgnored%! ^<- The 3 trailing spaces above are ignored.
echo/
endlocal
pause
Running this small batch code results in the output:
var=text
var = text
var1=and more text
var2="and more text"
var3="text with 1 trailing space"
var3="text with 1 trailing space" <- Do you see the trailing space?
Hello ! <- Where does the space come from?
There is a trailing space after Hello in this code snippet.
Hi! <- The 3 trailing spaces above are ignored.
Enclosing variable=value in quotes can be done even if the text itself contains 1 or more double quotes.
set "Quote=""
This line defines the variable Quote with the value ". Command set interprets everything after first equal sign left to last double quote as value to assign to variable with name between the first quote and first equal sign.
Note: A string value with " inside and next & or && or || can be even on usage of set "variable=value" misinterpreted and so result in unexpected behavior as it can be seen on running a batch file with following two lines:
#echo off
set "Variable=Value with one double quote in the middle" & echo Oh, there is something wrong here!"
Value with one double quote in the middle" & echo Oh, there is something wrong here! is the string to assign to the environment variable, but assigned to the variable is just Value with one double quote in the middle and the rest of the line after " in the middle and after & interpreted as conditional operator and not literally is interpreted as additional command to execute by cmd.exe. The same problem exists with && or || after a " with 0 or more spaces/tabs between. This problem is not caused by command set. It is caused by Windows command processor which splits the line up into a command line with set and one more command line with echo with conditional execution of the echo command line.
Variable assignment with disabled command extensions
The command syntax set "variable=value" cannot be used if the command extensions are disabled with setlocal DisableExtensions in the batch file (or in Windows registry which is very uncommon and never seen by me on any Windows computer). A syntax error would be the result on execution of the batch file.
It is only possible to use set variable=value with command extensions disabled whereby the value can contain also double quotes and care must be taken on trailing spaces/tabs as they are also assigned to the environment variable.
Run in a command prompt window cmd /? and setlocal /? for more information about command extensions and which commands are affected by command extensions. Note: The output list of affected commands misses exit as described in answers on Where does GOTO :EOF return to?
Variable assignment via arithmetic expression
Using command set with option /A changes completely the parsing of second argument, i.e. the string after set /A. With option /A as first argument the second string is interpreted as arithmetic expression and being therefore processed completely different than on assigning a string value to an environment variable. Environment variables are always of type string and never of type integer.
The usage of option /A requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
It is in most cases not recommended to just assign a number to an environment variable using an arithmetic expression, i.e. using set /A var=1. set "var=1" or just set var=1 (and no trailing whitespaces) are a little bit faster because environment variables are always of type string.
In an arithmetic expression whitespaces are interpreted as delimiters for variable names, numbers and operators. For that reason the command line set /A var = 1 does not define a variable with name VARSpace with the string Space1 as set var = 1 does. set /A var = 1 defines a variable with name VAR with string value 1 after converting 1 from string (batch file contains 1 as character with hexadecimal code value 31) to integer with value 1 and back to a string with the two values 0x31 and 0x00 (string terminating null).
Variable assignment via a prompt
Also using command set with option /P changes the parsing of the
string after variable name and equal sign. The string after the variable name and the equal sign is interpreted as prompt text to output and not as string to assign to the environment variable.
The environment variable gets assigned the string entered by prompted user (or redirected from a file or command/application), or in case of user does not enter anything before pressing RETURN or ENTER, keeps its current value respectively is still undefined if not defined before the prompt.
The usage of option /P requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
Most used syntax for prompting a user for a string is:
set /P var="Please enter something: "
The command set removes in this case automatically the double quotes around the prompt text before printing to handle STDOUT (console window if not redirected).
But working is also:
set /P "var=Please enter something: "
Please read this answer for more details about prompt text parsing and how to output a prompt text with surrounding double quotes.
You need to remove whitespace before and after =:
set "var=text"
echo %var%
text

Adding and Removing text from %var% - Batch - Simple

I was wondering whether someone could simply explain to me how to Add and Remove specific keywords/text from a Variable in batch...
You can use text replacement: set var=%var:foo=% to remove foo from %var%.
Environment variable substitution has been enhanced as follows:
%PATH:str1=str2%
would expand the PATH environment variable, substituting each
occurrence of "str1" in the expanded result with "str2". "str2" can
be the empty string to effectively delete all occurrences of "str1"
from the expanded output. "str1" can begin with an asterisk, in which
case it will match everything from the beginning of the expanded
output to the first occurrence of the remaining portion of str1.
To add things to an environment variable you can either add it at the beginning or end:
set "var=beginning %var%"
set "var=%var% end"
or muck around with substrings if you need something in the middle:
set "var=%var:~0,5% middle %var:~5%"

Why is no string output with 'echo %var%' after using 'set var = text' command in cmd? [duplicate]

This question already has answers here:
Defining and using a variable in batch file
(4 answers)
Closed 4 years ago.
I set a variable in cmd with the set command, and tried to echo it.
Here is an example:
C:\Users\Logan>set var = text
C:\Users\Logan>set var
var = text
C:\Users\Logan>echo %var%
%var%
C:\Users\Logan>
Is there a way to force the cmd to echo the variable and not the raw text?
Assigning a value/string to an environment variable
It is best to use following syntax with command extensions enabled to define or modify an environment variable:
set "var=text"
The command is set and the parameter is "variable=value".
The parameter string can be enclosed in double quotes as on all commands as long as command extensions are enabled as by default.
If the double quotes are not used around variable=value, command set interprets everything to end of line after the first equal sign including not visible spaces and horizontal tabs at end of line as string value to assign to the variable.
The name of the variable starts with first non whitespace character (after double quote if used) and ends left to first equal sign. The value assigned to the variable starts right of first equal sign and ends at end of line or last double quote.
set VAR = TEXT
The command line above creates an environment variable with name VARSpace and assigns the string SpaceTEXT to this variable.
The usage of
set var="text"
is often not correct as this results in assigning to variable var the text with the quotes included and all trailing spaces and tabs. Referencing now var on another code line with surrounding quotes often results in an error message as the variable holds itself the text already with quotes. For more details see the answer on How to set environment variables with spaces?
Example:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "var=text"
set "var = text"
set "var1=and more text"
set var2="and more text"
set var3="text with 1 trailing space"
set var
echo var3=%var3%^<- Do you see the trailing space?
echo/
set UnwantedSpaceVar=Hello
echo %UnwantedSpaceVar%! ^<- Where does the space come from?
echo/
echo There is a trailing space after Hello in this code snippet.
echo/
set "TrailingSpacesIgnored=Hi"
echo %TrailingSpacesIgnored%! ^<- The 3 trailing spaces above are ignored.
echo/
endlocal
pause
Running this small batch code results in the output:
var=text
var = text
var1=and more text
var2="and more text"
var3="text with 1 trailing space"
var3="text with 1 trailing space" <- Do you see the trailing space?
Hello ! <- Where does the space come from?
There is a trailing space after Hello in this code snippet.
Hi! <- The 3 trailing spaces above are ignored.
Enclosing variable=value in quotes can be done even if the text itself contains 1 or more double quotes.
set "Quote=""
This line defines the variable Quote with the value ". Command set interprets everything after first equal sign left to last double quote as value to assign to variable with name between the first quote and first equal sign.
Note: A string value with " inside and next & or && or || can be even on usage of set "variable=value" misinterpreted and so result in unexpected behavior as it can be seen on running a batch file with following two lines:
#echo off
set "Variable=Value with one double quote in the middle" & echo Oh, there is something wrong here!"
Value with one double quote in the middle" & echo Oh, there is something wrong here! is the string to assign to the environment variable, but assigned to the variable is just Value with one double quote in the middle and the rest of the line after " in the middle and after & interpreted as conditional operator and not literally is interpreted as additional command to execute by cmd.exe. The same problem exists with && or || after a " with 0 or more spaces/tabs between. This problem is not caused by command set. It is caused by Windows command processor which splits the line up into a command line with set and one more command line with echo with conditional execution of the echo command line.
Variable assignment with disabled command extensions
The command syntax set "variable=value" cannot be used if the command extensions are disabled with setlocal DisableExtensions in the batch file (or in Windows registry which is very uncommon and never seen by me on any Windows computer). A syntax error would be the result on execution of the batch file.
It is only possible to use set variable=value with command extensions disabled whereby the value can contain also double quotes and care must be taken on trailing spaces/tabs as they are also assigned to the environment variable.
Run in a command prompt window cmd /? and setlocal /? for more information about command extensions and which commands are affected by command extensions. Note: The output list of affected commands misses exit as described in answers on Where does GOTO :EOF return to?
Variable assignment via arithmetic expression
Using command set with option /A changes completely the parsing of second argument, i.e. the string after set /A. With option /A as first argument the second string is interpreted as arithmetic expression and being therefore processed completely different than on assigning a string value to an environment variable. Environment variables are always of type string and never of type integer.
The usage of option /A requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
It is in most cases not recommended to just assign a number to an environment variable using an arithmetic expression, i.e. using set /A var=1. set "var=1" or just set var=1 (and no trailing whitespaces) are a little bit faster because environment variables are always of type string.
In an arithmetic expression whitespaces are interpreted as delimiters for variable names, numbers and operators. For that reason the command line set /A var = 1 does not define a variable with name VARSpace with the string Space1 as set var = 1 does. set /A var = 1 defines a variable with name VAR with string value 1 after converting 1 from string (batch file contains 1 as character with hexadecimal code value 31) to integer with value 1 and back to a string with the two values 0x31 and 0x00 (string terminating null).
Variable assignment via a prompt
Also using command set with option /P changes the parsing of the
string after variable name and equal sign. The string after the variable name and the equal sign is interpreted as prompt text to output and not as string to assign to the environment variable.
The environment variable gets assigned the string entered by prompted user (or redirected from a file or command/application), or in case of user does not enter anything before pressing RETURN or ENTER, keeps its current value respectively is still undefined if not defined before the prompt.
The usage of option /P requires enabled command extensions as otherwise the command set ignores the rest of the line completely without any error message.
Most used syntax for prompting a user for a string is:
set /P var="Please enter something: "
The command set removes in this case automatically the double quotes around the prompt text before printing to handle STDOUT (console window if not redirected).
But working is also:
set /P "var=Please enter something: "
Please read this answer for more details about prompt text parsing and how to output a prompt text with surrounding double quotes.
You need to remove whitespace before and after =:
set "var=text"
echo %var%
text

Splitting the parameter in a batch file multiple times

Sample batch execution:
test.bat /s v1.1 1,3,4,5
I want to split the parameter into three tokens using space as a delimiter. The result should be:
1st token = /s
2nd token = /v1.1
3rd token = 1,3,4,5
Then the 3rd token will be split again using comma as a delimiter
The code below splits the arguments using common delimiters such as space, comma, etc.
#ECHO OFF
SET PARAMS=
:_PARAMS_LOOP
SET PARAMS=%PARAMS%%1
ECHO %1
SHIFT
IF NOT "%1"=="" GOTO _PARAMS_LOOP
Execution:
test.bat /s v4.1 1,2,3,4
Result:
/s
v4.1
1
3
4
5
I just want to use space as a delimiter, then in the 3rd token(1,3,4,5) I will split it again using comma as a delimiter and echo each of it.
The issue is that cmd recognizes a space, tab, comma, semicolon, or equals sign as command line delimiters unless they are wrapped in doublequotes.
Delimiters
Some characters in the command line are ignored by batch files,
depending on the DOS version, wether they are "escaped" or not, and
often depending on their location in the command line:
commas (",") are replaced by spaces, unless they are part of a string
in doublequotes
semicolons (";") are replaced by spaces, unless they
are part of a string in doublequotes
"=" characters are sometimes
replaced by spaces, not if they are part of a string in doublequotes
the first forward slash ("/") is replaced by a space only if it
immediately follows the command, without a leading space
multiple spaces are replaced by a single space, unless they are part of a
string in doublequotes
tabs are replaced by a single space
leading spaces before the first command line argument are ignored
I know of several occasions where these seemingly useless "features" proved very
handy. Keep in mind, though, that these "features" may vary with the
operating systems used.
More on command line parsing can be found on the PATH and FOR
(especially FOR's interactive examples) pages.
http://www.robvanderwoude.com/parameters.php

Resources