Basically I'm trying to do !var1:SomeText=!var2!! but this code doesn't work. What am I missing?
Batch Scripting Help - Replace Substring of a DelayedExpansion Var with another DelayedExpansion Var
2.5k views Asked by Kigen At
1
There are 1 answers
Related Questions in VARIABLES
- .bat file - How can I return the value of a variable whose name depends on another variable concatenated with a string in a batch file?
- Accessing Secret Variables in Classic Pipelines through Java app in Azure DevOps
- Does tensorflow have a way of calculating input importance for simple neural networks
- Can you define a variable in ranges in java
- How to only estimate neonatal mortality using syncmrates in Stata?
- PHP string variable to multiple rows in table sql insert
- Good practices for variables in Laravel's layout files
- Variable in Python going up by more than 1 at a time
- Accessing a variable from a string
- Encapsulation does not seem to work in dart
- TypeError: indice_delete() takes 0 positional arguments but 3 were given
- Altova Mapforce - How to use results from Tokenize at the same time in a database call?
- Powershell v5 - variable name replacement when referring to WPF objects
- Use javascript variable in document.querySelector (howTo)
- usage of multinomial assign javascript?
Related Questions in BATCH-FILE
- .bat file - How can I return the value of a variable whose name depends on another variable concatenated with a string in a batch file?
- Discordbot(Python) who should start bat file(Minecraft server) can't find user_jvm_args.txt file
- Set req query output to a variable
- bat file creates a "corrupt" zip
- How to list several items in the dialog box for execution?
- "if contains" with forbidden special characters
- Overlaying frame number with ffmpeg
- Batch Script-Powershell MessageBox | How do I set TopMost within PS command line of Batch?
- Batch file no longer works correctly in Windows 11
- Trying to launch batch file from powershell, and immediately closes
- How to automate an SSH login with a batch file?
- Having trouble executing my program from a jar, using Jinput
- How can I unload Visual Studio projects via batch file/developer command prompt?
- How to use goto in nested loop in .bat script window
- How can I run this Powershell function from a batch file on windows?
Related Questions in SUBSTRING
- Algorithm for finding the largest common substring for n strings using Rabin-Karp function
- Unable to download CSV file from web URL with runtime using python
- Is there any possible way to remove the 1st character of a String using O(1) time complexity in C++?
- Split string based on delimiter into specific substrings in python stored in multiple columns
- Can you replace a substring from a regex match?
- Check Groovy string if it matches dynamically changing substring
- Lookup every character in string and replace with character from another string
- How to make pattern matching efficient for large text datasets
- SQL - Select only records where field contains either a given string explicitly OR or a range of strings within which given string falls
- Word Count in C
- Dynamic starting position in substring and dynamic length
- split string in powershell using delimiter
- Pandas - find all Rows where special Columns contain a part of text
- Searching into an array of long strings specific things. Then save it on a JSON Object
- Substring issue when combined with map or reduce. Am I doing something wrong?
Related Questions in WINDOWS-SCRIPTING
- Batch Script-Powershell MessageBox | How do I set TopMost within PS command line of Batch?
- Windows Post Patch Report not showing available/pending updates
- Exiftool - Batch join tags keywords from JSON to jpg files
- How do I create a powershell script to set default file type (.ica specifically) to open with a .exe located in C:\program files (x86)\
- How to add Double quotes to Array elements in Powershell console?
- Can Windows 11 Sound and Display settings be scripted?
- Powershell script to close specific user share drive session
- PowerShell Script to Replace non-HTML Tags
- search a folder recursively to list the file names which contains the string windows
- Logon scripts are running with admin powershell by default can this be changed?
- Microsoft Excel cannot paste the data. FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
- How to automatically set the Application Pool Identity, User Name & Password
- Printing borderless with PowerShell script
- I need help figuring out where my code is getting hung up at
- Trigger jenkins Job with Azure AD Auth
Related Questions in DELAYEDVARIABLEEXPANSION
- Why ^^! and not ^! for literal escapes during delayed variable expansion?
- Batch to read out strings from txt with special characters
- Batch loop to create folders from a list containing environment variables
- Struggling to perform string substitution within a nested for loop
- Batch - return value from inside a loop
- Batch - Replace a String in a Loop
- Return a value from a called batch file label
- Batch - Get System Language of current running System
- delaydexpansion and endlocal conflict, any solution?
- Cannot parse file names with ! in them but double quoted?
- Delayed Expansion Inside Loop with Arithmetic Operations on Time Values
- Problem saving string variables in .bat script
- How to use delayed expansion on a variable like %%a or %1?
- What is the difference between % % and ! ! in a batch file?
- Getting delayed expansion value to function output
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
The order of expansion is critical when doing a search and replace operation that uses a variable for the search and/or the replace. The inner variable must be expanded before the outer search and replace expansion takes place. Trying to used delayed expansion for both obviously can't work because the delayed expansion occurs at one point in time.
The classic method for expansion of a variable within another variable uses delayed expansion for the outer, and normal for the inner:
echo !var1:SomeText=%var2%!"I am going to assume you wanted to use delayed expansion for both for a reason. Perhaps the expansion occurs within a block of code and one of the variables was set in the same block. Normal expansion won't work because it can't see the value that was assigned within the block until after the block concludes.
Solution 1
One way to solve the problem is to use CALL:
This works as follows:
The percent phase of the parser converts double percents into single percents, resulting in
call echo %var1:SomeText=!var2!%The delayed expansion expands !var2!, resulting in
call echo %var1:SomeText=ReplacementText%The CALL ECHO is executed and an additional level of percent processing takes place. The search and replace expansion is executed, resulting in
ResultOfSearchAndReplacebeing echoed to the screen.This works, but it is relatively slow. It also can have problems if the expanded value has special characters like
>,&or|. I rarely use this technique.Solution 2
The fast and more reliable method is to do the expansion in two steps. First transfer the value of
!var2!to a FOR variable. You can then use the FOR variable as the replacement string and use delayed expansion for the second step. This completely avoids the more brittle percent expansion.The above works because FOR variable expansion takes place before delayed expansion.
This is by far my preferred method to attack this problem.
For a more thorough explanation of the various phases of the batch parser, refer to jeb's answer to How does the Windows Command Interpreter (CMD.EXE) parse scripts?