我有一个批处理文件脚本显示我的adb工具的输出。
FOR /F "skip=1 delims=~" %%x IN ('adb devices -l') DO echo %%x
2行输出
0123456789ABCDEF device product:java_joyplus_qb7 model:TM702B4_3G device:java_joyplus_qb7 transport_id:12
F9NPFP084096 device product:WW_P023 model:P023 device:P023_1 transport_id:11
我想解析 "transport_id: "后面的非空格子串,第一行我想得到12,第二行想得到11。我怎么能做到这一点?
如果我没有理解错的话,下面的内容是指 批处理文件 应该输出你需要的信息。
@Echo Off
For /F "Skip=1 Tokens=1*" %%G In ('adb.exe devices -l') Do (Set "DI=%%H"
SetLocal EnableDelayedExpansion
For /F %%I In ("!DI:*transport_id:=!") Do EndLocal & Echo %%I)
Pause
而且,如果你想从 cmd:
For /F "Skip=1Tokens=1*" %G In ('adb.exe devices -l')Do @Set "DI=%H"&For /F %I In ('Cmd /D/V/C Echo "!DI:*transport_id:=!"')Do @Echo %~I
您可以轻松提取 都 变量,无论其位置如何,都能显示出你想要的东西。
@echo off
setlocal EnableDelayedExpansion
FOR /F "skip=1 delims=" %%a IN ('adb devices -l') DO (
for %%b in (%%a) do for /F "tokens=1,2 delims=:" %%x in ("%%b") do set "%%x=%%y"
echo Product=!product!
echo Transport=!transport_id!
)
例如:
Product=java_joyplus_qb7
Transport=12
Product=WW_P023
Transport=11
SETLOCAL EnableDelayedExpansion
REM …
FOR /F "skip=1 delims=~" %%x IN ('adb devices -l') DO (
set "_ID="&set "_transport_id="
call :parse "" "%%~x"
echo transport_id !_transport_id! (!_ID!^)
)
REM … remaining part of your script here …
goto :eof
:parse
if "%~2"=="" goto :eof
for /F "tokens=1,*" %%G in ("%~2") do (
if "%~1"=="" (
set "_ID=%%~G"
call :parse "%%~G" "%%~H"
) else (
for /F "tokens=1,2 delims=: " %%g in ("%~2") do (
if /I "%%~g"=="transport_id" (
set "_transport_id=%%~h"
) else (
call :parse "%%~G" "%%~H"
)
)
)
)
goto :eof
用下面的脚本进行测试,其中有一个硬编码的假设 adb
输出 adb
安装)。)
@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
(
REM last token
set "_ID="&set "_transport_id="
call :parse "" "0123456789ABCDEF device product:java_joyplus_qb7 model:TM702B4_3G device:java_joyplus_qb7 transport_id:12"
echo transport_id !_transport_id! (!_ID!^)
REM penult token
set "_ID="&set "_transport_id="
call :parse "" "F9NPFP084096 device product:WW_P023 model:P023 transport_id:11 device:P023_1"
echo transport_id !_transport_id! (!_ID!^)
REM elsewhere token
set "_ID="&set "_transport_id="
call :parse "" "abc123def567 transport_id:10 device product:XX_P023 model:P023 device:P023_2"
echo transport_id !_transport_id! (!_ID!^)
REM nowhere token
set "_ID="&set "_transport_id="
call :parse "" "noTransportId sport_id:10 device product:XX_P023 model:P023 device:P023_2"
echo transport_id !_transport_id! (!_ID!^)
)
goto :eof
:parse
if "%~2"=="" goto :eof
for /F "tokens=1,*" %%G in ("%~2") do (
if "%~1"=="" (
set "_ID=%%~G"
call :parse "%%~G" "%%~H"
) else (
for /F "tokens=1,2 delims=: " %%g in ("%~2") do (
if /I "%%~g"=="transport_id" (
set "_transport_id=%%~h"
) else (
call :parse "%%~G" "%%~H"
)
)
)
)
goto :eof
输出: D:\bat\SO\61588773.bat
transport_id 12 (0123456789ABCDEF) transport_id 11 (F9NPFP084096) transport_id 10 (abc123def567) transport_id (noTransportId)