Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用sed或grep提取_Regex_Linux_Sed_Awk_Grep - Fatal编程技术网

Regex 使用sed或grep提取

Regex 使用sed或grep提取,regex,linux,sed,awk,grep,Regex,Linux,Sed,Awk,Grep,我对grep和sed命令相当陌生。如何在bash脚本中使用grep或sed从核心0:+50.0°C(高=+80.0°C,临界=+90.0°C)中提取+50.0 acpitz-virtual-0 Adapter: Virtual device temp1: +50.0°C (crit = +89.0°C) temp2: +50.0°C (crit = +89.0°C) coretemp-isa-0000 Adapter: ISA adapter Core 0:

我对grep和sed命令相当陌生。如何在bash脚本中使用grep或sed从
核心0:+50.0°C(高=+80.0°C,临界=+90.0°C)
中提取
+50.0

acpitz-virtual-0
Adapter: Virtual device
temp1:        +50.0°C  (crit = +89.0°C)
temp2:        +50.0°C  (crit = +89.0°C)

coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +50.0°C  (high = +80.0°C, crit = +90.0°C)
Core 2:       +47.0°C  (high = +80.0°C, crit = +90.0°C)
Bash脚本:

#!/bin/bash

temp=`sed -n '/^Core 0:      $/,/^(high/p' ~/Desktop/sensors.txt`

echo $temp

使用
grep-oP
(PCRE regex):

或者,只是在awk中

awk '{ r = "^Core 0:" } { if(match($0,r)) { print $3 } }' [input]

这两个选项都将打印您似乎要查找的字段,并消除周围的空白。

使用grep传入perl regex标志,并使用以丢弃左侧行中不需要的部分

 grep -oP '^Core 0:\s+\K\+\d+[.]\d+?' 

为了完整性起见,这里尝试修复
sed
脚本

sed
是面向行的,因此您的尝试将从与第一个表达式匹配的任何内容(无论如何都不会匹配)打印到与第二个表达式匹配的下一行

(因此,换言之,
sed-n'/first/,/last/p'文件
将从
文件
的第一行打印匹配
first
,并在文件的后续输入行上找到
last
时停止。)

请尝试以下方法:

sed -n 's/^Core 0: *//;T;s/ (high.*//p' ~/Desktop/sensors.txt
这将用零替换第一个表达式。如果没有进行替换,
T
跳到脚本的末尾(隐式地什么也不做,只是从下一个输入行开始)。否则,我们有一个匹配项,所以我们也用零替换尾部,然后打印


。。。但是,并非所有的
sed
方言都有
T
命令,有些方言显然不喜欢用分号分隔的脚本。

关于需要提取的内容,您有更具体的规则吗?它总是紧跟在
核心0:
之后,但在
之前(
)吗?我只想提取核心0:和之间存在的任何内容。如果可能,消除核心0:和+50.0之间的额外空间(这是动态的)
grep-e'^Core 0:'[input]| awk'{print$3}
正在打印
设备(crit(crit adapter+50.0°C+47.0°C
。我只需要+50.0它看起来由于某种原因grep不起作用,而awk代码只是在所有行上运行。不知道为什么会发生这种情况,不过——两者在我的机器上都运行良好。只需
awk'/^Core 0:/{print$3}“输入”
更优雅、简洁、惯用。
 grep -oP '^Core 0:\s+\K\+\d+[.]\d+?' 
sed -n 's/^Core 0: *//;T;s/ (high.*//p' ~/Desktop/sensors.txt