barefly
barefly

Reputation: 378

Condensing down an awk / sed piped command

I have an ugly looking command that takes output from sensors and strips it of unneeded characters and decimal places, then prints it with awk with a trailing fahrenheit symbol. The command looks like this:

sensors -f | awk '/temp1/ { print $2 }' | sed 's/+//g' | awk '{ sub (/\..*/, ""); print $1 "°F" }'

Output from this command looks like this.

101°F

The command is a bit of a mess but it gets the job done, and considering my limited knowledge of awk and sed that is something to be said. I was hoping someone with a bit more knowledge could show me how this command could be condensed down, as I am unclear how to run an awk with a search pattern, followed by a replace, and print. Any help would be appreciated. Thanks!

EDIT: Output of sensors -f as requested.

acpitz-virtual-0
Adapter: Virtual device
temp1:       +112.2°F  (crit = +203.0°F)
temp2:       +118.6°F  (crit = +221.0°F)

coretemp-isa-0000
Adapter: ISA adapter
Core 0:      +119.0°F  (high = +212.0°F, crit = +212.0°F)
Core 1:      +121.0°F  (high = +212.0°F, crit = +212.0°F)

Upvotes: 3

Views: 121

Answers (4)

Cabbie407
Cabbie407

Reputation: 237

This is less messy:

sensors -f | awk '/temp1/{ printf "%d°F\n", $2 }'

It works, because awk begins parsing the string $2 at the beginning and stops if it doesn't fit the requirements anymore. So, as an example, "+234.76abcd" * 1 is parsed to the number 234.76. The same thing happens here when it looks for an integer to fill the %d in the format string.

I'd prefer:

sensors -f | awk '/temp1/{ print int($2) "°F" }'

Upvotes: 2

NeronLeVelu
NeronLeVelu

Reputation: 10039

# Posix
sensors -f | sed -e '/^temp1:[[:blank:]]\{1,\}[+]/ !d' -e 's///;s/F.*/F/'
# GNU
sensors -f | sed '/^temp1:[[:blank:]]+[+]/!d;s///;s/F.*/F/'

another sed approach

Upvotes: 4

Cyrus
Cyrus

Reputation: 88776

With GNU sed:

sensors -f | sed -nE 's/^temp1: +\+([^.]+).[0-9]*(°F).*/\1\2/p'

Output:

112°F

Upvotes: 3

anubhava
anubhava

Reputation: 785631

You can use use this single awk command instead:

sensors -f | awk '/temp1/ { gsub(/^\+|\.[[:digit:]]+/, "", $2); print $2 }'

Output:

112°F

gsub(/^\+|\.[[:digit:]]+/, "", $2); will replace any leading + or decimal values from the reported temperature.

Upvotes: 3

Related Questions