假设我的文件中“%userprofile%~.txt”下有以下内容:
Monitor: Generic PnP Monitor
Device: \\.\DISPLAY1
Adapter: Intel(R) UHD Graphics 630
(1920 x 1080 x 32 bpp) 60Hz default up, attached (-1920,0)
Monitor: Generic PnP Monitor
Device: \\.\DISPLAY4
Adapter: NVIDIA Quadro P2000
(1280 x 1024 x 32 bpp) 60Hz default up, attached (1920,0)
Monitor: Generic PnP Monitor
Device: \\.\DISPLAY8
Adapter: DisplayLink USB Device
(1920 x 1080 x 32 bpp) 60Hz default up, attached, primary (0,0)文本块的数量可以变化。
我想要得到的是出现在每个块的最后一行的两个坐标中的第一个,所以根据示例,结果应该是:
-1920
1920
0要在批处理脚本中执行此操作,我首先通过初始for循环分析文件,该循环检索包含字符串"default up,attached“的行。
然后,对于每个检索到的字符串,我将搜索最后一次出现(之后的文本。
从前面的结果中,我搜索第一次出现,之前的文本。
我找到了一个在for循环之外工作的解决方案(参见下面标有**的行),但我希望这些行在循环内。我尝试了下面标有*的行,但是脚本退出了,并且我不知道错误是什么。希望是一小块遗失的碎片。请忍受我的低批量脚本知识。
我的脚本:
@echo off
setlocal EnableDelayedExpansion
set Cnt=0
FOR /F "tokens=*" %%a IN ('findstr "default up, attached" "%userprofile%\~.txt"') DO (
set /a Cnt+=1
set result=%%a
for %%b in ("%result:(=" "%") do set "result=%%~b" <= * THESE LINES DON'T WORK!!!
for /f "tokens=1 delims=," %%c in ("%result%") do set "result=%%~c" <= * THESE LINES DON'T WORK!!!
call Set Monitors[%%Cnt%%]=!result!
)
for %%b in ("%Monitors[1]:(=" "%") do set "Monitors[1]=%%~b" <= ** THESE LINES WORK
for %%b in ("%Monitors[2]:(=" "%") do set "Monitors[2]=%%~b" <= ** THESE LINES WORK
for %%b in ("%Monitors[3]:(=" "%") do set "Monitors[3]=%%~b" <= ** THESE LINES WORK
for /f "tokens=1 delims=," %%c in ("%Monitors[1]%") do set "Monitors[1]=%%~c" <= ** THESE LINES WORK
for /f "tokens=1 delims=," %%c in ("%Monitors[2]%") do set "Monitors[2]=%%~c" <= ** THESE LINES WORK
for /f "tokens=1 delims=," %%c in ("%Monitors[3]%") do set "Monitors[3]=%%~c" <= ** THESE LINES WORK
echo %Monitors[1]%
echo %Monitors[2]%
echo %Monitors[3]%
pause发布于 2021-09-10 16:30:16
另一种方法是使用powershell regex来完成此操作:
@Echo off
:# Replace with actual filename
Set "File=%~dp0in.txt"
Set "Content=\(-?\d+,\d+\)$"
Set "Prefix=^.*?,+ \w+ \("
Set "Suffix=,\d*\)"
:# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-7.1
Set "[i]=1"
For /f "Delims=" %%G in ('
powershell -nologo -noprofile -c ^
"(GC "%File%") -match '%Content%' | ForEach {"$_" -replace '%Prefix%' -replace '%Suffix%'}
')Do Call Set /A "[i]+=1","Monitor[%%[i]%%]=%%G"
Set Monitor[
Goto :Eof发布于 2021-09-10 19:00:15
您可以使用圆括号和逗号作为分隔符来获取所需的值。因为您的一个输入行中有额外的逗号,所以这将需要两个嵌套的FOR命令。第一个FOR将通过括号将其拆分,并将给出第二组括号之间的所有内容。然后将该输出放入另一个FOR命令中,以拆分逗号处的值。
@echo off
REM use the parentheses as a delimiter
FOR /F "tokens=3 delims=()" %%G IN ('findstr "default up, attached" "file.txt"') DO (
REM USE the comma as a delimiter for the final split up of the variable.
FOR /F "TOKENS=1 delims=," %%H IN ("%%~G") DO ECHO %%~H
)https://stackoverflow.com/questions/69134343
复制相似问题