1

I only want to select the first occurrence of a pattern on the line, e.g. the '53.0' instead I get:

$ echo  "Core 0: +53.0°C (high = +80.0°C, crit = +100.0°C)" |
  sed -n 's/.*+\([0-9.]*\).*/\1/p'

which, for me, prints: 100.0 when I expected: 53.0.

I am using Ubuntu 18.04.3 LTS.

What am I missing?

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
RogerM
  • 11
  • 1

2 Answers2

2

Could you please try following.

echo  "Core 0: +53.0°C (high = +80.0°C, crit = +100.0°C)" | 
sed 's/[^+]*+\([^ ]*\).*/\1/'

OR in case you don't want ° in output then try following.

echo  "Core 0: +53.0°C (high = +80.0°C, crit = +100.0°C)" |  
sed 's/[^+]*+\([^°]*\).*/\1/'

Explanation of above code:

I have used sed's capability of saving matched regex into temp buffer memory and given it a reference as \1 to print it later.

Following explanation is only for explaining purposes to run code use above code please.

sed '          ##Starting sed program here.
s              ##Using s option for substitution method by sed on Lines of Input_file.
/[^+]*+        ##Using regex to have till 1st occurrence of + here.
\([^ ]*\)      ##Using memory buffer saving capability of sed to save matched regex in it.
               ##Have used regex to match everything till occurrence of space. Which should catch 1st temperature.
.*             ##Mentioning .* to match all rest line.
/\1/'          ##Now substituting whole line with 1st buffer matched value.

Explanation of why OP's code not working: Since OP is using .*+ in his/her attempt which is a GREEDY match so hence it is matching the last occurrence of + thus it is giving last temperature value.

Note: Added link provided by Sundeep sir in comments for Greedy match understanding.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

Quite simple to do with awk (no need for complex regex)

echo  "Core 0: +53.1°C (high = +80.0°C, crit = +100.0°C)" | awk '{print $3+0}'
53.1

Print the third field $3, then the +0 is used to get only the digits, it trims of °C

Jotne
  • 40,548
  • 12
  • 51
  • 55