grep 文件并仅打印该行中的第 n 个单词

rod*_*dee 5 linux shell

文件“测试”的内容:

[]# 0-CPU4    8.9%,   9336/832, 0x5ffe9b88--0x5ffec000
[]# 0-CPU0    13.5%, aa: 4/3, xvl: 35
[]# 0-CPU1    8.6%, SM: 1/4, ovl: 60
[]# 0-CPU0    38.8%, SM: 1/4, ovl: 62
Run Code Online (Sandbox Code Playgroud)

形成这个文件,我想要最后一个CPU0的百分比,即38(忽略小数点)

我使用下面的 shell 命令,效果很好,想知道是否有更好的方法。

grep CPU0 test | tail -1 | awk '/0-CPU0/ {print $3}' | sed 's/\..*//'
#above command prints "38"
Run Code Online (Sandbox Code Playgroud)

zed*_*xus 4

假设您的数据位于名为 test 的文件中:

cat test | grep CPU0 | tail -1 | awk '{ printf("%d", $3) }'

grep CPU0 test | tail -1 | awk '{ printf("%d", $3) }' - condensed

awk ' /CPU0/ {a=$3} END{ printf("%d", a) }' test - more condensed
Run Code Online (Sandbox Code Playgroud)

它能做什么:

  • cat 将输出测试文件中的所有行
  • grep CPU0 将仅输出包含 CPU0 的那些行
  • tail -1 将给出 grep 输出的最后一行
  • awk 将按[]# 0-CPU0 38.8%, SM: 1/4, ovl: 62空格分割
  • 第一项是[]#,第二项是 0-CPU0,第三项是 38.8%
  • awk 的 printf%d只会给你 38