findstr returns nothing in windows batch script
-
04-06-2021 - |
Question
In windows cmd, temp dir is set to
C:\spec>echo %temp%
C:\Users\mahmood\AppData\Local\Temp
also there is a file %temp%\specdev.txt which contain
C:\spec>type %temp%\specdev.txt
c:\cpu
Now when I execute this command
findstr -r "^[a-zA-Z]:$" %temp%\specdev.txt >nul 2>&1
it doesn't return anything!!
C:\spec>findstr -r "^[a-zA-Z]:$" %temp%\specdev.txt >nul 2>&1
C:\spec>
What is the problem?? Can you explain what does this command do? it is part of a batch script.
Solution
You cannot see any results because all console outputs are redirected to NUL: the last part of the command >nul
redirects standard output to NUL and 2>&1
redirects error output to standard output (therefore, NUL).
Because this command is part of a script, it does not mean it is useless: FINDSTR sets the global environment variable %ERRORLEVEL%
to 0 when it finds a match and set it to 1 when doesn't find. Thus, a script can send all output to NUL (not to clog user screen) and check %ERRORLEVEL%
to verify the results.
About the pattern this command is searching for, "^[a-zA-Z]:$"
means that it searches for a line that only contains a single letter from "a" to "z" (uppercase and lowercase) and ends with a colon ":". Thus, the file %temp%\specdev.txt
you described will not match the expression.
OTHER TIPS
The problem is that the string doesn't match the regular expression, which matches lines that consist of nothing but a single letter followed by ':'
character.
So now the question is, what pattern do you really want to match? Maybe you want:
"^[a-zA-Z]:"
which will match lines that start with a letter followed by a ':'
(but can then have other characters following that on the line). But I suspect you want something more complex.
Try this code instead:
findstr -r "^[a-zA-Z]*$" %temp%\specdev.txt >nul 2>&1