- How to substitute variable contents in a Windows batch file
- 7 Answers 7
- What is the best way to do a substring in a batch file?
- 3 Answers 3
- How to see if a string contains a substring using batch
- 4 Answers 4
- Windows bat script for loop if substring in string
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged windows batch-file cmd or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Batch file: Find if substring is in string (not in a file)
- 10 Answers 10
How to substitute variable contents in a Windows batch file
I’m writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from other variables
Works fine (output is ‘The fat cat’ and ‘The thin cat’
However, if ‘fat’ or ‘thin’ are in variables, it doesn’t work
I know this can be done as I’ve seen it in blogs before, but I never saved the link to the blogs.
Anyone have any ideas?
PS. I’m running the scripts on Windows 7
PPS. I know this is easier in Perl/Python/other script language of choice, but I just want to know why something that should be easy is not immediately obvious.
PPPS. I’ve also tried the scripts with delayed expansion explicitly turned on
This makes no difference.
7 Answers 7
Please try the following:
Copy and paste the code into Notepad and save it as a batch file.
I hope you’re convinced!
Use CALL. Put the following in a batch script and run it:
As stated here, we use the fact that:
internal_cmd Run an internal command, first expanding any variables in the argument.
In our case internal_cmd is initially set a=%%a:%b%^=%c%%%.
After expansion internal_cmd becomes set a=%a:fat=thin%.
Thus, in our case running
is equivalent to running:
The problem with:
is that it tries to expand two variables: a: and =thin with a c constant string between them.
The first command outputs:
which is piped into a second command shell for evaluation.
And. How about this?
Recently I came accross the same situation..As said earlier, I used like below and worked.
I try to avoid using SETLOCAL enabledelayedexpansion . ENDLOCAL all (or nearly all) the time, because usually I want to set or modify a few variables and I want the new values to be available in other areas of the script or after the batch script ends (SETLOCAL|ENDLOCAL will forget about any new variables or changes to variables in the «SETLOCAL» part of the script. Sometimes that’s handy, but for me I find it’s usually not.
Currently I use the method described by @Zuzel, but before I knew about that method, I used to use this, which is very similar (but looks a bit more complicated):
the output from running the script:
I like this method because you can call external programs (or internal commands) using modified variables and also capture and process the output of the command (line by line).
But, Zuzel’s method is simpler and cleaner for most situations, including the one you described.
Note:
Both of these methods (and also SETLOCAL enabledelayedexpansion . ENDLOCAL , of course), only work correctly if run from within a batch script. If you try to use either of these two methods («call» or «for») directly in a command prompt window, you will get something different from what the output was running from a script.
For example, run this as a script:
the output from running the script:
Now, run those commands directly in a command prompt window:
examine the before and after output lines from the command prompt window:
Notice that the substitutions are made correctly, but also notice that with running these commands directly in the command prompt window, it adds a set of «%» (percent signs) before and after the expected value each time the substitution is made. So, it makes it difficult to test any of these methods directly in the command prompt window.
What is the best way to do a substring in a batch file?
I want to get the name of the currently running batch file without the file extension.
Thanks to this link, I have the file name with the extension. but what is the best way to do a substring in a batch file?
Or is there another way to get the file name w/o the extension?
It is safe to assume 3 letter extensions in this scenario.
3 Answers 3
Well, for just getting the filename of your batch the easiest way would be to just use %
will output the name (without the extension) of the currently running batch file (unless executed in a subroutine called by call ). The complete list of such “special” substitutions for path names can be found with help for , at the very end of the help:
In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:
The modifiers can be combined to get compound results:
To precisely answer your question, however: Substrings are done using the :
will extract 5 characters from position 10 in the environment variable %var% .
NOTE: The index of the strings is zero based, so the first character is at position 0, the second at 1, etc.
To get substrings of argument variables such as %0 , %1 , etc. you have to assign them to a normal environment variable using set first:
The syntax is even more powerful:
-7% extracts the last 7 characters from %var%
%var:
0,-4% would extract all characters except the last four which would also rid you of the file extension (assuming three characters after the period [ . ]).
How to see if a string contains a substring using batch
Currently trying to see if a string, in this case the current line of a text file, contains a substring # . I am new to batch, so I am not sure exactly how I would do something like this. Here is the code set substring = #
4 Answers 4
Batch is sensitive to spaces in a SET statement. SET FLAG = N sets a variable named «FLAG Space » to a value of » Space N»
The syntax SET «var=value» (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned. set /a can safely be used «quoteless».
As an alternative to find , you can use string substitution, like this:
This approach uses delayed environment variable expansion. Type setlocal /? in command prompt to find out how to enable it, and set /? to see how it works (read variables like !string! instead of %string% ) and what it means. set /? also describes the string substitution syntax.
I had to create a function:
Remember it is not case sensitive by default. Add the word true to the end of the Call if you would like to be case sensitive such as:
And these Functions to the bottom of your Batch File.
And remember you MUST add «SETLOCAL ENABLEDELAYEDEXPANSION» to the top of your batch file or else none of this will work properly.
Windows bat script for loop if substring in string
I’m trying to modify the for loop on a list of files from here, adding to it, a check if a sub-string exists in the file name:
for /r %%i in (*) do echo %%i
How can I modify the above windows bat script to check if a sub-string exists in a file name or not?
2 Answers 2
I believe you are looking for this:
Or if you are using a batch file:
Here is my directory structure:
Output of running the following command:
Notice there is no notthisone.txt listed.
One way is to use string substitution (check [SS64]: Variable Edit/Replace or [SO]: Batch file: Find if substring is in string (not in a file) for more details).
Because it happens in a for loop, Delayed Expansion ([SS64]: EnableDelayedExpansion) must be taken into account.
For example, the following code filters file names that contain «text» and discards the rest (each found file name is printed at the beginning).
Output:
Not the answer you’re looking for? Browse other questions tagged windows batch-file cmd or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Batch file: Find if substring is in string (not in a file)
In a batch file, I have a string abcdefg . I want to check if bcd is in the string.
Unfortunately it seems all of the solutions I’m finding search a file for a substring, not a string for a substring.
Is there an easy solution for this?
10 Answers 10
Yes, you can use substitutions and check against the original string:
The %str1:bcd=% bit will replace a bcd in str1 with an empty string, making it different from the original.
If the original didn’t contain a bcd string in it, the modified version will be identical.
Testing with the following script will show it in action:
And the results of various runs:
A couple of notes:
- The if statement is the meat of this solution, everything else is support stuff.
- The x before the two sides of the equality is to ensure that the string bcd works okay. It also protects against certain «improper» starting characters.
You can pipe the source string to findstr and check the value of ERRORLEVEL to see if the pattern string was found. A value of zero indicates success and the pattern was found. Here is an example:
When this is run in CMD.EXE, we get:
I usually do something like this:
I don’t know if this is the best way.
For compatibility and ease of use it’s often better to use FIND to do this.
You must also consider if you would like to match case sensitively or case insensitively.
The method with 78 points (I believe I was referring to paxdiablo’s post) will only match Case Sensitively, so you must put a separate check for every case variation for every possible iteration you may want to match.
( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )
In addition, many times it is preferable to match command output, a variable in a loop, or the value of a pointer variable in your batch/CMD which is not as straight forward.
For these reasons this is a preferable alternative methodology:
Use: Find [/I] [/V] «Characters to Match»
[/I] (case Insensitive) [/V] (Must NOT contain the characters)
As mentioned this is great for things which are not in variables which allow string substitution as well: