我想使用
获取电池电压dumpsys battery
输出是某行
Current Battery Service state:
AC powered: false
USB powered: false
Wireless powered: false
Max charging current: 0
Max charging voltage: 0
Charge counter: 2208619
Overload: false
USB overheat: false
Extension: 0
PowerJacketExist: false
PowerJacketStatus: 0
PowerJacketLevel: 0
PluginStatus: false
Unsupport Charger: false
status: 3
health: 2
present: true
level: 71
scale: 100
voltage: 4008
temperature: 340
technology: Li-ion
mLedLogType: -1
CutoffVoltage: 0
在“电压:”之后,我只需要4008(此值可以更改) 我尝试了这种grep方法,但是我猜它不起作用,因为有多个匹配项
dumpsys battery | grep voltage
答案 0 :(得分:1)
能否请您尝试一次。这应该显示所有出现的字符串voltage:
的值。
awk '/^ +voltage:/ && $NF!=0{print $NF}' Input_file
OR
your_command | awk '/^ +voltage:/ && $NF!=0{print $NF}'
或者,如果您不希望电压为零,那么请尝试以下操作。
awk '/^ +voltage:/ && $NF!=0{print $NF}' Input_file
如果您想第二次出现电压串,请尝试以下操作。
awk '/^ +voltage:/ && ++count==2{print $NF}' Input_file
说明: 现在也添加了上述代码的说明。
awk ' ##Starting awk program here.
/^ +voltage:/{ ##Checking condition if a line consist string voltage: then do following.
print $NF ##This statement will be execute ONLY when previous condition is TRUE and it will print last field value here.
}' Input_file ##Mentioning Input_file name here.
第二个解决方案: 现在也使用sed
命令添加解决方案。
sed -n '/^ +voltage:/s/.*: //p' Input_file
OR
your_command | sed -n '/^ +voltage:/s/.*: //p'
答案 1 :(得分:0)
如果您的grep
支持,则可以使用PCRE和正向后视:
$ grep -oP "(?<=^ voltage: ).*" file
4008
答案 2 :(得分:0)
$ awk -F'(^|:) *' '{f[$2]=$3} END{print f["voltage"]}' file
4008
$ awk -F'(^|:) *' '{f[$2]=$3} END{print f["Max charging voltage"]}' file
0
$ awk -F'(^|:) *' '{f[$2]=$3} END{print f["status"], f["health"], f["scale"]}' file
3 2 100
或创建所有字段的CSV(例如,导入到Excel):
$ awk -F'(^|:) *' -v OFS=',' '
{ keys[NR]=$2; vals[$2]=$3 }
END {
for (i=2; i<=NR; i++) {
printf "%s%s", keys[i], (i<NR ? OFS : ORS)
}
for (i=2; i<=NR; i++) {
printf "%s%s", vals[keys[i]], (i<NR ? OFS : ORS)
}
}
' file
AC powered,USB powered,Wireless powered,Max charging current,Max charging voltage,Charge counter,Overload,USB overheat,Extension,PowerJacketExist,PowerJacketStatus,PowerJacketLevel,PluginStatus,Unsupport Charger,status,health,present,level,scale,voltage,temperature,technology,mLedLogType,CutoffVoltage
false,false,false,0,0,2208619,false,false,0,false,0,0,false,false,3,2,true,71,100,4008,340,Li-ion,-1,0