【问题标题】:Assign awk multiple variables分配 awk 多个变量
【发布时间】:2015-02-05 12:17:01
【问题描述】:

我正在使用这个命令来检查所有 sshd 进程和 CPU 使用情况以及 sshd 守护进程的 CMD:

ps -C sshd -o %cpu,cmd

输出示例:

%CPU CMD
 0.0 sshd: root [priv]
 0.0 sshd: aadmin@pts/1

之后我用过:

ps -C sshd -o %cpu,cmd | awk '!/%CPU/ {print $1, $3}'

输出:

0.0 root
0.0 aadmin@pts/1

要对 CPU USAGE 和第三行进行排序,我想要分配 awk 输出变量,以便在多个进程和单独的行中具有这样的输出。

CPU_USAGE=0.0 USER=root
CPU_USAGE=0.0 USER=aadmin@pts/1

我尝试使用 awk -v 将变量分配给 awk 但没有成功

【问题讨论】:

  • 问题是如何让你的输出看起来像那样?
  • 也许我在这里遗漏了一些东西,但您不能将您的 print 更改为 print "CPU_USAGE="$1, "USER="$3 吗?
  • @EtanReisner 是的,像这样 CPU_USAGE=0.0 USER=root CPU_USAGE=0.0 USER=aadmin@pts/1
  • 不清楚这与变量有什么关系。您能否更新您的问题以解释您的意思?
  • 目前还不清楚它与To sort CPU USAGE and third line 有什么关系。排序什么?第三行是什么?

标签: bash awk


【解决方案1】:
ps -C sshd -o %cpu,cmd | awk '!/%CPU/ {printf("CPU_USAGE=%s USER=%s\n", $1, $3)}'

您只需格式化 print 语句,为此,请使用 printf

或更短:

ps -C sshd -o %cpu,cmd | awk '!/%CPU/ {print "CPU_USAGE="$1, "USER="$3}'

希望这是你想要的。否则您的问题不清楚...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多