【问题标题】:Need to "grep" multiple output需要“grep”多个输出
【发布时间】:2016-09-29 09:36:31
【问题描述】:

使用此命令 (upower -i /org/freedesktop/UPower/devices/battery_BAT1) 我的终端显示以下输出:

  native-path:          BAT1
  vendor:               LG
  power supply:         yes
  updated:              mar 31 may 2016 12:45:15 CEST (101 seconds ago)
  has history:          yes
  has statistics:       yes
  battery
    present:             yes
    rechargeable:        yes
    state:               fully-charged
    warning-level:       none
    energy:              50,4088 Wh
    energy-empty:        0 Wh
    energy-full:         51,4522 Wh
    energy-full-design:  48,1 Wh
    energy-rate:         6,29 W
    voltage:             8,313 V
    percentage:          97%
    capacity:            100%
    icon-name:          'battery-full-charged-symbolic'

我需要获取一个包含输出数据的数组。像这样的东西:[BAT1, LG, yes, [...], 100%, 'battery-full-charged-symbolic']

有什么办法吗?

【问题讨论】:

  • 你的意思是 Bash 数组吗?

标签: shell ubuntu sed grep battery


【解决方案1】:

您的输出是典型的基于列的文本。 (分隔符为:)。您可以使用 awk 将其格式化为您想要的格式。

upower cmd...|awk -F':\\s*' '{printf "%s%s",(NR==1?"[":", "), $2}END{print "]"}'

会给你:

[BAT1, LG, yes, mar 31 may 2016 12, yes, yes, , yes, yes, fully-charged, none, 50,4088 Wh, 0 Wh, 51,4522 Wh, 48,1 Wh, 6,29 W, 8,313 V, 97%, 100%, 'battery-full-charged-symbolic']

【讨论】:

  • 哦,现在可以了。但我真正想要的是用一个数组存储所有这些输出。有可能吗?
  • 我不知道你说的是哪个上下文的“数组”。它提供了与您所需的输出格式相同的输出格式。
【解决方案2】:

你可以试试这样的:

 var = ( $(upowerOutput | grep -oE ':.+$' | sed -e 's/^[ \t:]*//') )

grep 部分获取必填字段,sed 用于修剪前导空格,:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-25
    • 2023-01-22
    • 1970-01-01
    • 2013-05-13
    • 2018-01-08
    • 2018-09-16
    • 2014-08-05
    • 1970-01-01
    相关资源
    最近更新 更多