【问题标题】:AWK - match multiple patterns and print resultsAWK - 匹配多个模式并打印结果
【发布时间】:2019-11-17 12:26:36
【问题描述】:

利用我有限的脚本知识.. 我整理了一个期望脚本来在特定设备上运行一些命令。输出如下,并从所有设备保存到一个文件中(我只是列出了 2 个设备作为示例)。

l

lssystem | grep -i physical
physical_capacity 82.85TB
physical_free_capacity 20.50TB
IBM_FlashSystem:SU73VAWFS15:config>
lssystem | grep -i physical
physical_capacity 82.85TB
physical_free_capacity 21.12TB
IBM_FlashSystem:SU73VAWFS16:config>

我想要的是从输出中获取一些值并将它们显示在行中,由“,”分隔:

SU73VAWFS15,82.85TB,20.50TB
SU73VAWFS16,82.85TB,21.12TB

【问题讨论】:

    标签: shell awk


    【解决方案1】:

    有很多方法可以做到这一点,这里有一个基于 util 的方法,(假设输入没有意外):

    lssystem | grep -i physical |
    tr ': ' '\t' | cut -f 2 | xargs | { read a b c ; echo "$c,$a,$b" ; }
    

    ...甚至:

    lssystem | grep -i physical |
    xargs | { IFS=' :' read a b c d e f g ; echo "$f,$b,$d" ; }
    

    【讨论】:

      【解决方案2】:

      我相信请求是将组合输出转换为单个 CSV 文件,因为使用“期望”执行的命令不能直接执行。以下是重新格式化组合输出的小脚本。

      awk -v OFS="," '
      $1 == "lssystem" {
          key = cap = free = ""
      } 
      $1 == "physical_capacity" { cap = $2 }
      $1 == "physical_free_capacity" { free = $2 }
      $1 ~ /config>$/ {
          split($1, a, ":" ) ;
          key = a[2] ;
          print key, cap, free
          key = cap = free = ""
      }
      ' < input-file
      

      小建议:通过多个系统收集数据时,最好创建某种形式的块,这样可以更容易地使用各种工具解析数据,例如:

      === BEGIN name-of-host
      lssystem | grep -i physical
      physical_capacity 82.85TB
      physical_free_capacity 20.50TB
      IBM_FlashSystem:SU73VAWFS15:config>
      === END
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        相关资源
        最近更新 更多