in batch file extract substring from a variable that is contained between double quotes
- User
in batch file extract substring from a variable that is contained between double quotes
- Assistant
in batch file extract substring from a variable that is contained between double quotes
To extract a substring enclosed in double quotes from a variable in a Windows batch file, you can use the FOR /F command with properly escaped delimiters. Here's how you can do it:
@echo off
setlocal EnableDelayedExpansion
rem Define your variable with text containing double quotes
set myvar=Some text "desired substring" some more text
rem Use FOR /F to parse the variable and extract the substring
for /F tokens^=2^ delims^=^" %%A in ("%myvar%") do (
set between=%%A
)
rem Display the extracted substring
echo The text between the quotes is: "!between!"
Explanation:
Set the Variable:
set myvar=Some text "desired substring" some more text
This sets up a variable %myvar% containing a string with a substring enclosed in double quotes.
Use FOR /F Loop:
for /F tokens^=2^ delims^=^" %%A in ("%myvar%") do (
set between=%%A
)
for /F reads the contents of %myvar%.tokens=2 tells the loop to select the second token that results after splitting the string.delims=" specifies that the double quote " is the delimiter. Note that the double quote is escaped using ^ to prevent syntax issues.%%A is the variable that stores the selected token inside the loop.%%A, which we then assign to the variable between.Display the Result:
echo The text between the quotes is: "!between!"
This echoes the extracted substring. Note that EnableDelayedExpansion allows us to use !between! to access the variable's value inside the loop.
Important Notes:
Escaping Characters: In batch scripting, special characters like double quotes need to be escaped using the caret ^ when used in for loops to avoid parsing errors.
Tokens and Delimiters: The tokens and delims options in the FOR /F command let you specify how to split the input string. By setting tokens=2 and delims=", you're telling the script to extract the second piece of text that appears between the specified delimiter, which is the double quote.
Delayed Variable Expansion: Enabling delayed expansion with setlocal EnableDelayedExpansion allows you to safely access variables that are modified within loops using !variable! syntax.
Example Output:
The text between the quotes is: "desired substring"
This method efficiently extracts the substring enclosed in double quotes from your variable in a batch file.
Not yet included in a published release.