Quote:
Originally Posted by Aleron Ives
If any Linux gurus out there can tell me how I could intercept the output of cat and format it nicely instead of displaying the raw numbers, I'd be interested to try that.
|
Depends on what's available. If units is available then something like:
Code:
# Example just echoing a number to test the concept.
# Use 'units' --terse mode.
# Convert from uV to V.
# Then echo it along with a literal V.
echo $(units -t "$(echo 3707800) uV" V) V
# result: 3.7078 V
# Replacing the call to echo with your call to cat:
echo $(units -t "$(cat /sys/class/power_supply/battery/voltage_now) uV" V) V
If units is not available but sed is available, and we are just dividing by 1e6 or 1e3 (which seems to be the case) then perhaps something like:
Code:
# The idea is to look for 6 or 7 digits, and insert a dot before the final 6 digits.
# If it was 6 digits then a leading 0 is inserted before the decimal.
# Trailing zeroes in the fractional part are stripped.
# If this results in a number like "3." then a single trailing zero is added, e.g. "3.0".
# Finally the line has the units appended on.
# Example using echo:
echo 3707800 | sed -E -e 's/([0-9]?)([0-9]{6})/\1.\2/; s/^\./0./; s/\.([0-9]*[1-9])?0+/.\1/; s/\.$/.0/; s/$/ V/'
# result: 3.7078 V
# With the actual file:
cat /sys/class/power_supply/battery/voltage_now | sed -E -e 's/([0-9]?)([0-9]{6})/\1.\2/; s/^\./0./; s/\.([0-9]*[1-9])?0+/.\1/; s/\.$/.0/; s/$/ V/'
Dividing by 10e3 is similar:
Code:
# Here if the result has no fractional part it is omitted instead of shown as ".0".
# Example using echo:
echo 1429000 | sed -E -e 's/([0-9]{3,4})([0-9]{3})/\1.\2/; s/^\./0./; s/\.([0-9]*[1-9])?0+/.\1/; s/\.$//; s/$/ mAh/'
# result: 1429 mAh
# With the actual file:
cat /sys/class/power_supply/battery/charge_now | sed -E -e 's/([0-9]{3,4})([0-9]{3})/\1.\2/; s/^\./0./; s/\.([0-9]*[1-9])?0+/.\1/; s/\.$//; s/$/ mAh/'