我是 ruby 的初学者,我对此感到非常困惑: 我需要“将 ethtool 输出拆分为不同的变量,
这就是我所做的:
[root@aptpka02 facter]# cat test.rb
interface = "enp8s0,enp9s0,enp1s0f0,enp1s0f1d1"
interface.split(',').each do |int|
# call ethtool to get the driver for this NIC
puts int
ifline = %x{/sbin/ethtool -i #{int} 2>/dev/null }
puts ifline
end
这是输出(仅针对一个接口(interface)):
enp1s0f1d1
driver: sfc
version: 4.0
firmware-version: 4.2.2.1003 rx1 tx1
bus-info: 0000:01:00.1
supports-statistics: yes
supports-test: yes
supports-eeprom-access: no
supports-register-dump: yes
supports-priv-flags: no
我只需要驱动程序和固件信息,我尝试将带有“or”的 grep 添加到命令执行中,如下所示:
interface.split(',').each do |int|
# call ethtool to get the driver for this NIC
puts int
ifline = %x{/sbin/ethtool -i #{int} 2>/dev/null | grep "driver\| firmware"}
puts ifline
end
但它不起作用,它打印一个空行。
最后,我想做的是:
[root@aptpka02 facter]# vim test.rb
interface = "enp8s0,enp9s0,enp1s0f0,enp1s0f1d1"
interface.split(',').each do |int|
# call ethtool to get the driver for this NIC
puts int
ifline = %x{/sbin/ethtool -i #{int} 2>/dev/null | grep "driver\| firmware"}.lines.each do | nicinfo|
if (nicinfo = driver)
driver = %x{/sbin/ethtool -i #{int} 2>/dev/null | grep 'driver: '}.chomp.sub("driver: ", "")
else
.
.
.
endif
end
您能给我一个如何继续的提示吗?
预先感谢您的帮助!
最佳答案
String#scan 对于这种情况很方便。假设您的示例数据位于名为 data 的字符串中:
data.scan(/(firmware-version: |driver: )(.+)/)
这输出一个数组:
=> [["driver: ", "sfc"], ["firmware-version: ", "4.2.2.1003 rx1 tx1"]]
关于ruby - 在 ruby 中 grep 或过滤 linux 输出以获取自定义事实,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51412234/