I am in the process of writing a simple script to grab battery information from acpi
so I can format and output it.
Currently, I am using cut
to grab this information, but as the battery state changes, cut
does not grab the correct data and instead will grab a portion of a string instead of the battery percentage.
When running acpi -b
, I get the following output:
Battery 0: Unknown, 100
Occasionally, acpi -b
will also return the following, or something similar if it is charging or discharging:
Battery 0: Discharging, 98%, 02:14:14 remaining
So, without using cut
, I’d like to be able to grab the data after the first comma, and, on occasion when present, grab the information between both commas. Right now, I am using sed to strip whitespace and the percentage sign from the output. Here is that command:
acpi -b | cut -c20-24 | sed 's/ //g;s/%//g'
Advertisement
Answer
You can use use this simple awk command:
s='Battery 0: Unknown, 100' awk -F',[[:blank:]]*' '{sub(/%/, "", $2); print $2}' <<< "$s" 100 s='Battery 0: Discharging, 98%, 02:14:14 remaining' awk -F',[[:blank:]]*' '{sub(/%/, "", $2); print $2}' <<< "$s" 98
awk breakup:
-F,[[:blank:]]* # makes comma followed by 0 or more spaces as field separator sub(/%/, "", $2) # remove trailing % print $2 # print 2nd field