【问题标题】:How to get the first numbers with SED linux如何使用 SED linux 获取第一个数字
【发布时间】:2010-03-20 11:26:06
【问题描述】:

“00:02.0 VGA 兼容控制器:InnoTek Systemberatung GmbH VirtualBox 图形适配器” 如何在 Bash 脚本中使用 SED 获得 VGA 之前的第一个数字? 谢谢!

【问题讨论】:

  • 根据答案的变化,您可以看到问题有点不明确。您提到了 bash,所以大概您想从 shell 中执行此操作。好的。您的源数据是否在变量中? ......来自管道? … 一份文件?你提到了sed。其他工具可以吗?您以单行输入为例。除非这是您将要处理的唯一数据,否则您真的应该给出多个示例,涵盖可能的输入范围(十六进制?、不同的尾随文本等)。您提到“VGA”,但除非这将成为您解析的每一行的一部分,否则它不是真正的要求。

标签: linux bash sed


【解决方案1】:
echo '00:02.0 VGA compatible bla bla bla' | sed -e 's/\(^[0-9:\.]*\).*/\1/'

【讨论】:

    【解决方案2】:
    $ s="00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter"
    $ echo $s| sed 's/\(.*\)VGA.*/\1/'
    00:02.0
    $ echo $s| sed 's/\([0-9]\+:[0-9]\+.*\)VGA.*/\1/'
    00:02.0
    $ echo $s| sed 's/VGA.*//'
    00:02.0
    

    或 awk

    $ echo $s| awk '{print $1}'
    00:02.0
    

    【讨论】:

      【解决方案3】:

      这也可以,但它依赖于你想要的数字后面有一个空格。

      sed 's/ .*//'
      

      【讨论】:

      • 当输入位于 ISO-8859-1 时,这对我来说因特殊字符而失败
      【解决方案4】:
      sed -e 's/\([0-9][0-9]:[0-9][0-9]\.[0-9]\).*/\1/'
      

      将保留数字。

      在脚本中,您可能会将返回字符串的命令传递给 sed,例如

      #!/bin/sh
      echo "00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter" | sed -e 's/\([0-9][0-9]:[0-9][0-9]\.[0-9]\).*/\1/'
      

      给了

      00:02.0
      

      【讨论】:

        【解决方案5】:

        恕我直言,使用 awk 代替 sed 会更简单,使用 awk 来满足您的需要:

        echo '00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter' | awk '{print $1}'
        

        比使用 sed 简单得多,不是吗?

        【讨论】:

          【解决方案6】:

          看起来您正在解析 lspci 输出。如果是这样,您可能想要查看应该更容易解析的-m 选项。如果您打算将 sed 与默认输出格式一起使用,那么您可以这样做:

          echo '00:02.0 VGA compatible controller: InnoTek Systemberatung GmbH VirtualBox Graphics Adapter' |
            sed -e 's/\([0-9a-fA-F][0-9a-fA-F]\):\([01][0-9a-fA-F]\)\.\([0-7]\) .*/\1 \2 \3/' |
            while read bus slot func; do 
              echo "bus: $bus; slot: $slot; func: $func"
            done
          

          如果你真的只阅读一行,你可以不使用 while 循环,但我将它包括在内,以防你真的想解析多行 lspci 输出。

          【讨论】:

            【解决方案7】:
            X="00:02.0 VGA compatible ..."
            set $X; echo $1

            【讨论】:

              【解决方案8】:

              试试看,sed -e 's/(^[0-9:.]<em>).</em>/\1/' urfile

              【讨论】:

              • 试试, cat urfile | sed -e 's/(^[0-9:\.]*).*/\1/'
              猜你喜欢
              • 2017-04-24
              • 2022-10-21
              • 2020-04-07
              • 2011-12-13
              • 2019-03-03
              • 1970-01-01
              • 1970-01-01
              • 2021-10-31
              • 2021-03-28
              相关资源
              最近更新 更多