Board logo

标题: [文本处理] 求助批处理提取指定行的指定字段并输出成变量 [打印本页]

作者: smtcao008    时间: 2023-10-28 11:13     标题: 求助批处理提取指定行的指定字段并输出成变量

不能插图也不能上传附件。。。。
如下是TXT 内容
Description,Value
Battery Name,02DL008
Manufacture Name,SMP
Serial Number, 2669
Manufacture Date,
Power State,"Charging, AC Power"
Current Capacity (in %),67.6%
Current Capacity Value,"29,920 mWh"
Full Charged Capacity,"44,260 mWh"
Designed Capacity,"50,450 mWh"
Battery Health,87.7%
Voltage,"12,868 millivolts "
Charge/Discharge Rate ,"32,852 milliwatts "
Chemistry ,LiP
Low Battery Capacity (1),200 mWh
Low Battery Capacity (2),"2,213 mWh"
Critical Bias,
Number of charge/discharge cycles,184
Battery Temperature,
Remaining battery time for the current activity (Estimated),
Full battery time for the current activity (Estimated),
Remaining time for charging the battery (Estimated),
Total  time for charging the battery (Estimated),

需要提取第11行Battery Health,87.7%和18行Number of charge/discharge cycles,184 的第二字节 并输出成变量,这个是做电池健康度监控使用的,Battery Health 必须大于95%,而充放电次数小于等于3, 但是我目前只能
  1. for /f "skip=10 delims=, tokens=2 " %%i in (scomma.txt) do echo %%i
复制代码
只能显示10行和之后的输出,百度了各种也成功不了,新手入门,难度太大,还请大佬不吝赐教!
作者: pd1    时间: 2023-10-28 11:28

  1. for /f "tokens=2 delims=," %%i in ('type scomma.txt^|find "Battery Health"') do echo %%i
复制代码

作者: terse    时间: 2023-10-28 11:30

  1. @echo off
  2. for /f "skip=10 delims=, tokens=1,* " %%i in (scomma.txt) do (
  3.       if /i "%%i" == "Battery Health" (set "Health=%%j") else if /i "%%i" == "Number of charge/discharge cycles" set "cycles=%%j"
  4. )
  5. if defined Health echo(%Health%
  6. if defined cycles echo(%cycles%
  7. pause
复制代码

作者: smtcao008    时间: 2023-10-28 11:39

回复 2# pd1


   学习了,谢谢
作者: smtcao008    时间: 2023-10-28 11:41

回复 3# terse


    这个运行提示 此处不该出现else   我研究下,感谢感谢!
作者: hfxiang    时间: 2023-10-28 11:58

回复 1# smtcao008
第3方工具sed( http://bcn.bathome.net/tool/4.9/sed.exe )比较方便
  1. sed -n "/Battery Health/p;\#Number of charge/discharge cycles#p" scomma.txt
复制代码

作者: smtcao008    时间: 2023-10-28 12:16

回复 6# hfxiang

谢谢!~~~
作者: Batcher    时间: 2023-10-28 12:56

回复 1# smtcao008


如果需要上传文件,可以用阿里云盘或百度网盘。

如果需要上传截图,可以找个图床,例如:
http://bbs.bathome.net/thread-60985-1-1.html
作者: terse    时间: 2023-10-28 14:46

回复 5# smtcao008
哦 可能环境问题 我这里运行没问题
作者: aloha20200628    时间: 2023-10-28 15:13


用findstr可一次锚定两个字段(不能忽略大小写)... 正好示例文件中没有重复关键词
  1. for /f "tokens=2 delims=," %%s in ('findstr "Health, charge/discharge" scomma.txt') do (echo,%%s)
复制代码

作者: terse    时间: 2023-10-28 15:51

回复 10# aloha20200628
严谨一点的话,最好加参数使用findstr,
  1. findstr /ibc:"Battery Health," /c:"Number of charge/discharge cycles," <scomma.txt
复制代码

作者: hfxiang    时间: 2023-10-28 16:27

回复 1# smtcao008
改了一下,不知道是否满足要求
  1. sed -rn "s/^Battery Health,(.*)%$/\1/p;s#^Number of charge/discharge cycles,(.*)$#\1#p" scomma.txt
复制代码

作者: smtcao008    时间: 2023-11-1 17:02

链接:https://pan.baidu.com/s/1hUqCjhlsLnp44ETG_T-tzg
提取码:1234
文档上传了百度网盘




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2