如何从命令行输出中提取值?

时间:2018-05-02 14:19:37

标签: parsing cmd elixir

我有一个功能,它可以获取所有USB连接设备的信息。

connected_devices = :os.cmd('usb-devices | grep -A 1 Product=')

它给了我'S: Product=EHCI Host Controller\nS: SerialNumber=0000:00:3d.0\n--\nS: Product=HP Truevision HD\nS: SerialNumber=201001010001\n--\nS: Product=xHCI Host Controller\nS: SerialNumber=0000:00:16.0\n--\nS: Product=iPhone\nS: SerialNumber=1d19427ba66fd77d12a836593af57c21c993f0c9\n--\nS: Product=xHCI Host Controller\nS: SerialNumber=0000:00:16.0\n'

从上述功能的输出中,我想提取ProductSerialNumber的值,以便我可以制作像[{product: something, serial_number: some number} ...]

这样的对象列表

如何从命令行输出中提取值?

1 个答案:

答案 0 :(得分:1)

我首先拆分--,以便每个块包含1个产品和1个serial_number。然后使用正则表达式从每个块中提取相关数据:

output = 'S:  Product=EHCI Host Controller\nS:  SerialNumber=0000:00:3d.0\n--\nS:  Product=HP Truevision HD\nS:  SerialNumber=201001010001\n--\nS:  Product=xHCI Host Controller\nS:  SerialNumber=0000:00:16.0\n--\nS:  Product=iPhone\nS:  SerialNumber=1d19427ba66fd77d12a836593af57c21c993f0c9\n--\nS:  Product=xHCI Host Controller\nS:  SerialNumber=0000:00:16.0\n'

output
|> List.to_string()
|> String.split("--")
|> Enum.map(fn chunk ->
  [_, product] = Regex.run(~r/Product=(.+)/, chunk)
  [_, serial_number] = Regex.run(~r/SerialNumber=(.+)/, chunk)
  %{product: product, serial_number: serial_number}
end)
|> IO.inspect

输出:

[
  %{product: "EHCI Host Controller", serial_number: "0000:00:3d.0"},
  %{product: "HP Truevision HD", serial_number: "201001010001"},
  %{product: "xHCI Host Controller", serial_number: "0000:00:16.0"},
  %{
    product: "iPhone",
    serial_number: "1d19427ba66fd77d12a836593af57c21c993f0c9"
  },
  %{product: "xHCI Host Controller", serial_number: "0000:00:16.0"}
]