我只想选择线上的第一个图案,例如我得到的是“ 53.0”:
$ echo "Core 0: +53.0°C (high = +80.0°C, crit = +100.0°C)" |
sed -n 's/.*+\([0-9.]*\).*/\1/p'
对于我来说,它打印:100.0,我期望的是:53.0。
我正在使用Ubuntu 18.04.3 LTS。
我想念什么?
答案 0 :(得分:2)
请您尝试以下。
echo "Core 0: +53.0°C (high = +80.0°C, crit = +100.0°C)" |
sed 's/[^+]*+\([^ ]*\).*/\1/'
或者如果您不想在输出中使用°
,请尝试执行以下操作。
echo "Core 0: +53.0°C (high = +80.0°C, crit = +100.0°C)" |
sed 's/[^+]*+\([^°]*\).*/\1/'
上述代码的解释:
我已经使用sed
的功能将匹配的正则表达式保存到临时缓冲存储器中,并为其指定了引用\1
以便以后打印。
以下说明仅是为了解释使用上述代码来运行代码的目的。
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.
OP为何不起作用的解释: 由于OP尝试使用.*+
的原因是GREEDY match,因此,与+
的最后一次出现匹配,因此它给出了最后一个温度值。
注意:已添加Sundeep先生提供的链接,以供理解贪婪的比赛之用。
答案 1 :(得分:0)
使用awk
非常简单(不需要复杂的正则表达式)
echo "Core 0: +53.1°C (high = +80.0°C, crit = +100.0°C)" | awk '{print $3+0}'
53.1
打印第三个字段$3
,然后使用+0
仅获取数字,它修剪°C