if "filename" contains "variable" do command - windows

I'm using the windows command line to write my first script. I'm trying to figure out how to run a command if a filename contains a specified variable and if it doesn't then to move on to the next part of the script. The filename Doesn't have to be an exact match, it just has to contain the variable in the specified order. I've been trying all kinds of commands for hours, but to no avail. This is only my second day of scripting so i'm not very knowledgeable on much. I'm looking for a command that will do this...
if "[Craig] Christmas Day - 2009 [720p].mkv" contains "[720p]" do command
I know that contains is not actually part of the if command but this is an example i thought would be the easiest to understand.
Can anyone help me out?

echo "thenameofyourfilewhichmaybeinavariable"|find /i "the substring" >nul
if errorlevel 1 (echo missing) else (echo found)
would be the classic way - but there are others.
(the /i means "case-insensitive")
see find /? and if /? from the prompt for documentation.

I'm not well versed in batch, but a cursory search reveals the findstr command. It seems to be capable of basic pattern matching.
If your system doesn't have findstr for whatever reason, you can use a messy equality check. Example adapted from this answer:
#setlocal enableextensions enabledelayedexpansion
set str1="[720p]"
if not x%str1:bcd=%==x%str1% echo 'It contains [720p]'
endlocal

Related

How to read specific string in txt file by using windows batch?

This is the content of my .txt file
123:456
789:333
I'm trying to use findstr to read string and search for 789:333, but it only print fist line 123:456
As I know, use cut can fulfill my requirement in Linux.
In Windows, do we have any method where we can search for a string in a file by using a batch-script?
it is simple. using a for loop.
#echo off
for /F "delims=" %%a in ('findstr /I "789:333" somefile.txt') do echo %%a
you can learn a lot about batch file commands by simply opening a cmd.exe window and typing help
It describes briefly each command and once you find one that you think might work, like let's say for, then you simply do for /? which will show you help content which will make your life easy.

Find and print the sub-string with wildcard character in a file on windows command prompt

I'm pretty sure this is a simple command but I just couldn't find it anywhere.
Example file content:
A-VERY-LONG-LINE-OF-GARBAGE-VERSION123-CONTINUE-LONG-LINE-OF-GARBAGE
1.)Assume the line is really really long
2.)I need to find out what version it is. I know it contains Version but I wouldn't know it is version123.
3.)What I want is a command that would go through the file looking for the sub-string "VERSION" and if it finds it prints out VERSION123 instead of the super duper long line that would most probably causes the system to freeze.
Thank you
Assuming that version is purely numeric and does not start with zero, the following should do it:
set VAR=A-VERY-LONG-LINE-OF-GARBAGE-VERSION123-CONTINUE-LONG-LINE-OF-GARBAGE
set /A VAR=%VAR:*VERSION=%
echo VERSION%VAR%
If there occur multiple VERSION portions, the first one is taken.
Note, that this works for Windows command prompt (cmd.exe) only, it will not work for MS-DOS (command.com) due to set /A which is not supported there (I'm even not sure whether the string substitution syntax works there)!
In case the version code is not purely numeric, you might use the following:
set VAR=A-VERY-LONG-LINE-OF-GARBAGE-VERSION123-CONTINUE-LONG-LINE-OF-GARBAGE
set VAR=%VAR:*VERSION=%
for /F "tokens=1 delims=- eol=-" %%L in ("%VAR%") do (set VAR=%%L)
echo VERSION%VAR%
This relies on the fact that the - character delimits the version code.
If you want to try this in the command prompt directly rather than in a batch file, replace %%L by %L (twice).

Can I search for multiple strings in one "find" command in batch script?

I have a windows batch script that will look for a string within a file
find /i "WD6" %Inputpath%file.txt
if %errorlevel% == 0 GOTO somestuff
Currently this is what my code looks like. I've come across a new string I want to search for in the same file and do the same action if it finds it, it stored it in a variable called %acctg_cyc% can I search for both strings in one line of code? I tried this:
find /i "WD6" %acctg_cyc% %Inputpath%file.txt
if %errorlevel% == 0 GOTO somestuff
But it seems to ignore the %acctg_cyc% and only look for "WD6" in file.txt. I tried testing where %acctg_cyc% is in file.txt and when it is not and it passes both times.
Any thoughts? I know I could do this in more lines of code but I'm really trying to avoid that right now. Maybe it's just not possible.
Thank you for any help!
find isn't very powerful. It searches for one string only (even if it is two words): find "my string" file.txt looks for the string my string.
findstr has much more power, but you have to be careful how to use it:
findstr "hello world" file.txt
finds any line, that contains either hello or world or both of them.
see findstr /? for more info.
Finding both words in one line is possible with (find or findstr):
find "word1" file.txt|find "word2"
finding both words scattered over the file (find or findstr):
find "word1" file.txt && find "word2" file.txt
if %errorlevel%==0 echo file contains both words
I tried findstr with multiple /C: arguments (one for each to be searched sentence) which did the trick in my case.
So this is my solution for finding multiple sentences in one file and redirect the output:
findstr /C:"the first search" /C:" a second search " /C:"and another" sourcefile.txt > results.txt
I used this. Maybe not much orthodox, but works!
It waits until browsers dismiss
:do_while_loop
rem ECHO LOOP %result%
rem pause
tasklist /NH | find "iexplore.exe"
set result=%ERRORLEVEL%
tasklist /NH | find "firefox.exe"
set result=%result%%ERRORLEVEL%
if not "%result%"=="11" goto :do_while_loop

`)`was unexpected at this time.

I am running a batch file on Windows 7 and running into this error (I have narrowed down the error to the following line):
FOR /F "delims=" %%I in ('echo %RegVal%') do set sasroot=%%~sI
Where Regval is the file path of a given software, which in this case (on my Win7 machine) is:
RegVal = C:\Program Files\SAS 9.2_M3_10w37\SASFoundation\9.2(32-bit)
This same script used to work on Windows Vista, although I suspect it may be that there a parenthesis in RegVal now as it was previousy C :\Program Files\SAS 9.2_M3_10w37\SASFoundation\ on my previous Vista machine.
You suspection is correct.
To get around it, enclose your variable into doublequotes (You remove them again with the ~ in the setcommand)
FOR /F "delims=" %%I in ('echo "%RegVal%"') do set sasroot=%%~sI
I suggest you create a file with the value of RegVal in it, then parse it using the FOR loop:
echo %RegVal%>C:\SomeFile.txt
FOR /F "delims=" %%I in (C:\SomeFile.txt) do set sasroot=%%~sI
This should help you get around your problem.
Stephan's solution is much simpler, but I'll explain my solution anyway, which might prove useful in some cases.
When the FOR command parses the data specified in the IN part using a command, it replaces the command with the result of the command, then runs the FOR command. For example, with the question above, the FOR command that will be executed after expanding echo %RegVal% is:
FOR /F "delims=" %%I in (C:\Program Files\SAS 9.2_M3_10w37\SASFoundation\9.2(32-bit)) do set sasroot=%%~sI
Thus, when the parser hits the first closing parenthesis, it will stop, thinking that everything it read before is the text to work on. However, in this case this is wrong, as the first closing parenthesis is part of the string to read; it doesn't indicate the end of the string.
When parsing a file with the FOR command, it will read each line, assign the predefined tokens with the correct values, then execute the code block that follows. Rinse and repeat for every line in the file. But in this case, it will not replace the IN part with each line; it will only parse it and assign values to the tokens. This is the reason why special characters (such as parenthesis) do not create parsing errors in this case.

Detecting how a batch file was executed

Assuming Windows, is there a way I can detect from within a batch file if it was launched from an open command prompt or by double-clicking? I'd like to add a pause to the end of the batch process if and only if it was double clicked, so that the window doesn't just disappear along with any useful output it may have produced.
Any clever ways to do this? I'm looking for solutions I could rely on to work on a machine that was configured more or less with default settings.
I just ran a quick test and noticed the following, which may help you:
When run from an open command prompt, the %0 variable does not have double quotes around the path. If the script resides in the current directory, the path isn't even given, just the batch file name.
When run from explorer, the %0 variable is always enclosed in double quotes and includes the full path to the batch file.
This script will not pause if run from the command console, but will if double-clicked in Explorer:
#echo off
setlocal enableextensions
set SCRIPT=%0
set DQUOTE="
#echo do something...
#echo %SCRIPT:~0,1% | findstr /l %DQUOTE% > NUL
if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1
:EXIT
if defined PAUSE_ON_CLOSE pause
EDIT:
There was also some weird behavior when running from Explorer that I can't explain. Originally, rather than
#echo %SCRIPT:~0,1% | findstr /l %DQUOTE% > NUL
if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1
I tried using just an if:
if %SCRIPT:0,1% == ^" set PAUSE_ON_CLOSE=1
This would work when running from an open command prompt, but when run from Explorer it would complain that the if statement wasn't correct.
Yes. Patrick Cuff's final example almost worked, but you need to add one extra escape, '^', to make it work in all cases. This works great for me:
set zero=%0
if [^%zero:~0,1%] == [^"] pause
However, if the name of the batch file contains a space, it'll be double quoted in either case, so this solution won't work.
Don't overlook the solution of having two batch files:
abatfile.bat and abatfile-with-pause.bat
The second simply calling the first and adding a pause
Here's what I use :
rem if double clicked it will pause
for /f "tokens=2" %%# in ("%cmdcmdline%") do if /i "%%#" equ "/c" pause
I use a parameter "automode" when I run my batch files from scripts.
set automode=%7
(Here automode is the seventh parameter given.)
Some code follows and when the file should pause, I do this:
if #%automode%==# pause
One easy way to do it is described here:
http://steve-jansen.github.io/guides/windows-batch-scripting/part-10-advanced-tricks.html
There is little typo in the code mentioned in the link. Here is correct code:
#ECHO OFF
SET interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L /I %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL%==0 SET interactive=1
ECHO do work
IF "%interactive%"==1 PAUSE
EXIT /B 0
Similar to a second batch file you could also pause if a certain parameter is not given (called via clicking).
This would mean only one batch file but having to specify a -nopause parameter or something like that when calling from the console.
crazy idea: use tasklist and parse it's results.
I've wrote in a test batch file:
tasklist > test.out
and when I double-clicked it, there was an additional "cmd.exe" process just before the tasklist process, that wasn't there when the script was run from command line (but note that might not be enough if someone opens a command line shell and then double-click the batch file)
Just add pause regardless of how it was opened? If it was opened from command prompt no harm done apart from a harmless pause. (Not a solution but just thinking whether a pause would be so harmful / annoying )

Resources