Use findstr regular expressions to search for patterns in piped results - batch-file

I want to search for the pattern (COM\d+) in the output of mode command. I have tried the:
mode | findstr /R (COM\d+)
But it doesn't return anything. I would appreciate if you could help me know what is the correct way to do this.
P.S.1 Thanks to the comments I now have the mode | findstr /RC:"COM[0-9*]" which yields the line with the given match. Now I need to find a way to print out just the match. maybe using the for /f ... in to loop the string?
P.S.2 I'm being told that mode | findstr /RC:"COM[123456789][0123456789]*" is a safer option.

Here's two simple examples according to my comments:
From the Command Prompt, to satisfy your cmd tag:
(For /F Delims^=: %A In ('Mode^|FindStr "COM[0-9]*:"')Do #For %B In (%A)Do #Set "var=%B")&Call Echo(%var%
From a batch file, to satisfy your batch-file tag:
#(For /F Delims^=: %%A In ('Mode^|FindStr "COM[0-9]*:"')Do #For %%B In (%%A)Do #Set "var=%%B")&Call Echo(%%var%%&Pause
To supplement my comment about WMI, you could alternatively try:
From the Command Prompt:
For /F Skip^=1Delims^= %A In ('WMIC Path Win32_SerialPort Get DeviceID 2^>Nul')Do #For %B In (%A)Do #Echo(%B
From a batch file:
#For /F Skip^=1Delims^= %%A In ('WMIC Path Win32_SerialPort Get DeviceID 2^>Nul')Do #For %%B In (%%A)Do #Echo(%%B&Pause

So, why not just use only one for loop command and addind \ for literal find COM+RegEx in FindStr by this: "\C\O\M[0-9*]."
Obs.: For some reason, the command line do not work for echoing in first run, the COM number for echo/%_com% command, only in second run work, but adding Call to echo/%_com% command, the result showing in first running...
In command line:
for /f "tokens=2delims=COM:" %i in ('mode ^| findstr /RC:"\C\O\M[0-9*]."') do set "_com=%i"&& call echo/%_com%
for /f "tokens=2delims=COM:" %i in ('mode ^| findstr /RC:"\C\O\M[0-9*]."') do set "_com=COM%i"&& call echo/%_com%
for /f "tokens=2delims=COM:" %i in ('mode ^| findstr /RC:"\C\O\M[0-9*]."') do set "_com=COM%i:"&& call echo/%_com%
result 1st line command: 3
result 2nd line command: COM3
result 3rd line command: COM3:
Or in batch file:
#echo off & setlocal enabledelayedexpansion
for /f "tokens=2delims=COM:" %%i in ('mode ^| findstr /RC:"\C\O\M[0-9*]."') do set "_com=%%i"&& echo/!_com!
for /f "tokens=2delims=COM:" %%i in ('mode ^| findstr /RC:"\C\O\M[0-9*]."') do set "_com=COM%%i"&& echo/!_com!
for /f "tokens=2delims=COM:" %%i in ('mode ^| findstr /RC:"\C\O\M[0-9*]."') do set "_com=COM%%i:"&& echo/!_com!
result 1st for command: 3
result 2nd for command: COM3
result 3rd for command: COM3:
See your self by command line:
mode | findstr /RC:"\C\O\M[0-9*]."
result: Status para dispositivo COM3:
So sorry my limited English

It sounds like you just want "COM1" or "COM3" as the output. If so, this'll do it:
for /f "tokens=4 delims=: " %A in ('mode ^| findstr /i /r "COM[0-9]*:"') do #echo %A
It'll produce the following output:
COM1

Related

assigning a piped command to the variable batch

I'm having trouble assigning a command that counts the number of times a file in a directory appears to a variable.
I found that I should do this - (^ |) but when I do it and echo the variable, nothing is displayed, and there should be a number of occurrences.
My code:
#echo off
setlocal enableextensions
for /f "tokens=*" %%i in ('dir /b C:\Users\AD10FC\IdeaProjects\collateral\db-resources\release | findstr /B "!first%!-" | find /c /v ""') do set VAR=%%i
echo %VAR%
There is no need to use findstr.exe in your code to filter the leading strings, because you can filter those directly in Dir:
#Echo Off
SetLocal EnableExtensions
Set "first=LeadingString"
For /F "EOL=? Delims=" %%G In ('"Dir /B /A:-D "%UserProfile%\IdeaProjects\collateral\db-resources\release\%first%-*" | "%SystemRoot%\System32\find.exe" /V /C """') Do Set "VAR=%%G"
Echo(%VAR%
Pause
Also for the specific task you're performing, you may find the following works better for you:
#Echo Off
SetLocal EnableExtensions
Set "first=LeadingString"
For /F %%G In ('""%SystemRoot%\System32\xcopy.exe" "%UserProfile%\IdeaProjects\collateral\db-resources\release\%first%-*" . /LQH"') Do Set "VAR=%%G"
Echo(%VAR%
Pause

How to trim string in command prompt?

I have a lot of shortcut urls in a directory.
C:\Users\Owner\Desktop\ReadItLaters>dir *.url /b
aaa.url
bbb.url
ccc.url
...
zzz.url
I want to pickup those url.
so I wrote command like this.
for %i in (*.url) do #type "%i" | find "URL="
that outputs like this.
URL=https://www.example.com/aaa.html
URL=https://www.example.com/bbb.html
URL=https://www.example.com/ccc.html
...
URL=https://www.example.com/zzz.html
It tastes nice. but I want to get url strings WITHOUT "URL=".
I wish to output like this.
https://www.example.com/aaa.html
https://www.example.com/bbb.html
https://www.example.com/ccc.html
...
https://www.example.com/zzz.html
How can I replace "URL=" to empty?
You can use substring, skipping the first 4 characters in your string: %_url:~4%
cmd/bat
for /f %%i in ('type *.url^|find "URL="')do set "_url=%%~i" && call echo/%_url:~4%
command-line
for /f %i in ('type *.url^|find "URL="')do set "_url=%~i" && call echo/%_url:~4%
Some further reading:
[√] Set
[√] For Loop
[√] For /F Loop
[√] Conditional Execution || && ...
[√] Substring in Set command (Refer: %_url:~4%)
use a for /f loop to process the lines:
for /f "tokens=2 delims==" %%a in ('type *.url 2^>nul^|find "URL="') do #echo %%a
or a bit saver (in case the URLs contain =)
for /f "tokens=1,* delims==" %%a in ('type *.url 2^>nul^|findstr /b "URL="') do #echo %%b
See for /? for details.
(Note: this is batch file syntax. If you want to use it directly on the command line, replace each %% with a single %)
You should be able to get the information for multiple URL files, without the need to nest two for loops. You can take advantage of FindStr's ability to search through multiple files directly.
batch-file:
#For /F "Tokens=1*Delims==" %%G In ('""%__AppDir__%findstr.exe" /IR "^URL=http" "*.url" 2>NUL"')Do #Echo %%H
cmd:
For /F "Tokens=1*Delims==" %G In ('""%__AppDir__%findstr.exe" /IR "^URL=http" "*.url" 2>NUL"')Do #Echo %H

Eliminate the extra spaces from WMIC

I am creating a script that will get the computer version and serial number, turn it into variables, and then combine them together to create the new hostname.
However, the WMIC command for the serial number returns "T300"-"FDHGFJ "
Running just the serial number WMIC alone (without the does not "wmic csproduct get version") does not include the extra spaces.
I've tried looping it around one more time as other posts suggest but no luck.
Below is the full code.
#ECHO ON
PUSHD "%~dp0"
setlocal EnableDelayedExpansion
for /f "usebackq skip=1 tokens=*" %%i in (`wmic bios get serialnumber ^| findstr /r /v "^$"`) do set "serialn=%%i"
for /f "usebackq skip=1 tokens=2 delims= " %%a in (`wmic csproduct get version ^| findstr /r /v "^$"`) do set "modeln=%%a"
ECHO "%modeln%"-"%serialn%" >>test.txt
POPD
exit
I want the final result to be "T300"-"FDHGFJ" as it might get implemented into a task sequence.
You can try a bit of a hack by setting the variable only if not defined. I removed "tokens=*" and "delims=" as that will get the entire line. We then just do substitution on whitespace.
#echo off
set serialn=
set modeln=
for /f "usebackq skip=1" %%i in (`wmic bios get serialnumber`) do if not defined serialn set "serialn=%%i"
for /f "usebackq skip=1" %%a in (`wmic csproduct get version`) do if not defined modeln set "modeln=%%a"
echo "%modeln: =%"-"%serialn: =%">>test.txt
Note the output of second string on my device wmic csproduct get version has only one value and therefore I had to change the string, if yours really has 2 tokens then you should use your original string:
for /f "usebackq skip=1 tokens=2" %%a in (`wmic csproduct get version`) do if not defined modeln set "modeln=%%a"
The wmic command with its get verb might pad the returned data by trailing SPACEs, which I assume you want to have removed without removing SPACEs in the returned values themselves.
To achieve this you need to change the output format by adding the VALUE option, like this:
#echo off
setlocal EnableDelayedExpansion
cd /D "%~dp0."
for /F "tokens=1* delims==" %%I in ('wmic BIOS get SerialNumber /VALUE') do for /F "delims=" %%K in ("%%J") do set "serialn=%%K"
for /F "tokens=1* delims==" %%I in ('wmic CSProduct get Version /VALUE') do for /F "delims=" %%K in ("%%J") do set "modeln=%%K"
>> "test.txt" echo "%modeln%"-"%serialn%"
endlocal
exit /B
In addition I changed the following:
I placed another for /F loop inside of the one that parses the wmic output in order to avoid Unicode-to-ASCII/ANSI conversion artefacts by for /F, like orphaned carriage-return characters;
I replaced the pushd/popd pair by cd /D, because setlocal/endlocal already localises the environment, including the current working directory;
I added an explicit endlocal just to explicitly end the environment localisation (although this would be done upon termination of the batch script anyway);
I replaced exit by exit /B in order to only quit the batch file but not the parent cmd instance;
I put the redirection portion >> "test.txt" in front of the echo command in order to avoid the trailing space between the last closing " and >> (in your code) to be returned too;
As my initial comment regarding using /Value has already been implemented into an answer, this one expands upon using the wmic CSV format:
#Echo Off
SetLocal DisableDelayedExpansion
Set "DWM=%__AppDir__%wbem"
Rem Fixes 'Invalid XSL format (or) file name' errors in some Windows versions.
Set "CSV="
For /F "Delims=" %%A In ('"Dir /B/S/A-D "%DWM%\csv.xsl" 2>Nul"'
)Do If Not Defined CSV Set "CSV=%%A"
If Not Defined CSV Exit /B
Set "Serial#=Null"
For /F "Skip=2Tokens=1*Delims=," %%A In (
'""%DWM%\wmic.exe" BIOS Get SerialNumber /Format:"%CSV%" 2>Nul"'
)Do For /F Tokens^=* %%C In ("%%~B")Do Set "Serial#=%%~C"
Set "Model#=Null"
For /F "Skip=2Tokens=1*Delims=," %%A In (
'""%DWM%\wmic.exe" CSProduct Get Version /Format:"%CSV%" 2>Nul"'
)Do For /F Tokens^=* %%C In ("%%~B")Do Set "Model#=%%~C"
Echo "%Model#%"-"%Serial#%">>"test.txt"
Pause

Get only numbers in version from dll file

I'm trying to get the vertion of a .dll file, but only the number of the version.
I find the code
wmic datafile where name='C:\\...\\MY_FILE.dll' get version
This code returns:
Version
3.56.0.1
I need the return to be only '3.56.0.1' and this could be saved in a variable for i'll can call in a echo after.
set var="HOW DO I DO?"
echo %var%
How can I get this?
I can use the code below too, but in this format I think its harder
wmic datafile where name='C:\\...\\MY_FILE.dll' get version /format:list
This code returns:
Version=3.56.0.1
And similarly to those posted, with minor differences.
A batch-file:
#For /F "Delims=" %%A In ('WMIC DataFile Where "Name='C:\\...\\MY_FILE.dll'" Get Version /Value 2^>Nul')Do #For /F "Tokens=*" %%B In ("%%A")Do #Set "%%B"
#Echo(%Version%&Pause
A cmd version:
For /F "Delims=" %A In ('WMIC DataFile Where "Name='C:\\...\\MY_FILE.dll'" Get Version /Value 2^>Nul')Do #For /F "Tokens=*" %B In ("%A")Do #Set "%B"
Where the variable %Version% should be set to the local environment.
You'll need to parse with a for /f.
And another for /f to repair broken WMIC output.
On cmdline (using a windows dll):
For /f "usebackqdelims=" %A in (`wmic datafile where name^='C:\\Windows\\System32\\authui.dll' get version /format:list^|findstr "Version"`) do #For /F "delims=" %B in ("%A") do #Set "%B"
set Version
Version=10.0.17134.1
In a batch file double the percent signs of the for meta variable(s)
So you would require a for loop to do this.. see more help on it by running for /? from cmd.exe
#echo off
for /f "tokens=1,* delims==" %%i in ('wmic datafile where name^="C:\\...\\MY_FILE.dll" get version /format:list') do if not defined var set var=%%j
echo %var%
Note that the help will not assist you with the caret escape character used on the = which however you can find help on here at SO.
You should use:
#echo off
for /F "delims== tokens=2" %%A IN ('wmic datafile where name^="C:\\...\\MY_FILE.dll" get version /format:list') do (
for %%B IN ("%%A") do set "var_name=%%~B"
)
echo %var_name%
which loops through your command and finds the second token according to the delimeter specified (=).
Due to wmic unusual line endings (<CR><CR><LF>), you should use a double for loop.
If you scripted in PowerShell, you could use:
$var = [Diagnostics.FileVersionInfo]::GetVersionInfo('C:/.../MY_FILE.dll').ProductVersion
If you want to do it in a .bat file script, there is some overhead.
C:>TYPE gv.bat
#ECHO OFF
FOR /F "delims=" %%v IN ('PowerShell -NoLogo -NoProfile -Command ^
"[Diagnostics.FileVersionInfo]::GetVersionInfo('C:/Windows/System32/dfscli.dll').ProductVersion"') DO (
SET "var=%%~v"
)
ECHO var is +++%var%+++
C:>CALL gv.bat
var is +++10.0.17763.1+++

Batch findstr to find a number

I'm trying to get the revision number from a svn update command output. In the file tmpFile.txt I've got the string At revision 58998.
I've run the following command:
findstr /r "\<[0-9][0-9]*\>" "tmpFile.txt"
and I've got
At revision 58998.
Also, running with
findstr /r /o "\<[0-9][0-9]*\>" "tmpFile.txt"
I get
0:At revision 58998.
What's going on and how can I get only the number?
FINDSTR prints out the entire line that matches. It is not able to extract just the matching portion of the line.
You can use FOR /F to parse the output and get just the number.
for /f "tokens=3 delims=. " %%A in (
'findstr /rc:"At revision [0-9][0-9]*\." "tmpFile.txt"'
) do echo %%A
Not a findstr solution, but it works :)
setlocal enabledelayedexpansion
for /f "tokens=3" %%a in (tmpFile.txt) do (
set num=%%a
set num=!num:.=!
)
echo !num!
This will also remove the . from the end.
If your not bothered about the . use
for /f "tokens=3" %%a in (tmpFile.txt) do echo %%a
or for cmd line (no batch)
for /f "tokens=3" %a in (tmpFile.txt) do echo %a

Resources