【问题标题】:Grep the first (2 digit) number after a \+ signgrep \+ 符号后的第一个(2 位)数字
【发布时间】:2016-01-27 01:56:34
【问题描述】:

TL:DR 我想要紧跟“+”号的任何行的前两个数字的语法。

给定以下文本(来自熟悉的实用程序):

power_meter-acpi-0
Adapter: ACPI interface
power1:        4.29 MW (interval = 4294967.29 s)

coretemp-isa-0000
Adapter: ISA adapter
Physical id 0:  +44.0°C  (high = +75.0°C, crit = +85.0°C)
Core 0:         +36.0°C  (high = +75.0°C, crit = +85.0°C)
Core 1:         +38.0°C  (high = +75.0°C, crit = +85.0°C)
Core 2:         +36.0°C  (high = +75.0°C, crit = +85.0°C)
Core 3:         +36.0°C  (high = +75.0°C, crit = +85.0°C)
Core 4:         +37.0°C  (high = +75.0°C, crit = +85.0°C)
Core 5:         +36.0°C  (high = +75.0°C, crit = +85.0°C)

coretemp-isa-0001
Adapter: ISA adapter
Physical id 1:  +43.0°C  (high = +75.0°C, crit = +85.0°C)
Core 0:         +36.0°C  (high = +75.0°C, crit = +85.0°C)
Core 1:         +38.0°C  (high = +75.0°C, crit = +85.0°C)
Core 2:         +36.0°C  (high = +75.0°C, crit = +85.0°C)
Core 3:         +37.0°C  (high = +75.0°C, crit = +85.0°C)
Core 4:         +36.0°C  (high = +75.0°C, crit = +85.0°C)
Core 5:         +37.0°C  (high = +75.0°C, crit = +85.0°C)

我需要找出有趣的数字,即 44、36、38、36、36、37 等...

在 Linux 的命令行中,我使用了sensors | awk '{ print $3 }' | egrep -o '\+..' | sed 's/^.//',它输出了 14 个有趣数字中的 12 个,但并不那么优雅。

【问题讨论】:

  • sensors | sed -r 's/^.*\+([[:digit:]]+)\.[[:digit:]].C .*/\1/'
  • @EdMorton 这是“太长了,没看过” - 提供一个摘要。

标签: linux awk command-line grep


【解决方案1】:

也许,在 awk 单行中:

sensors | awk -F'[+.]' '/\+/{print $2}'

假设数字以“+”开头。如果温度可能以负数开头,您可能需要添加:

sensors | awk -F'[-+.]' '/high/{print $2}'

真的,取决于您确定可以关闭的内容。

当然,如果温度真的从负值开始,您可能会遇到更大的问题。 :-)

【讨论】:

    【解决方案2】:

    您可以结合使用 sed 和 grep:

    $ sensors | sed 's/^[^+]*+\([0-9][0-9]\).*$/\1/g' | grep -o "^[0-9][0-9]$" 
    44
    36
    38
    36
    36
    37
    36
    43
    36
    38
    36
    37
    36
    37
    

    sed 命令将每一行映射到它的第一对数字。 grep 命令过滤掉不是两位数的每一行。

    【讨论】:

    • 如果从sed 中删除/g,则不需要grep,因为您不再进行全局替换
    • 仍然需要grep 来过滤掉空行和标题行。
    【解决方案3】:
    $ sed -n 's/[^+]*+\([0-9][0-9]\).*/\1/p' file
    44
    36
    38
    36
    36
    37
    36
    43
    36
    38
    36
    37
    36
    37
    

    【讨论】:

      【解决方案4】:

      如果我们利用第一个数字后面的某处有一个左括号但其他数字后面没有的事实,单个 grep 就可以做到:

      $ grep -oP '(?<=\+|-)\d+(?=\.\d°C\s+\()' infile
      44
      36
      38
      36
      36
      37
      36
      43
      36
      38
      36
      37
      36
      37
      

      使用 Perl 正则表达式引擎 (-P) 并仅提取匹配项 (-o):

      (?<=\+|=)        # Positive look-behind: + or -
      \d+              # The digits we're extracting
      (?=\.\d°C\s+\()  # Positive look-ahead: dot digit °C spaces and (
      

      【讨论】:

      • 当有人使用他们的正则表达式时,我真的很感激 - 这是一个钝脚本。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2016-08-12
      相关资源
      最近更新 更多