linux - AWK,在每列奇怪的行为之前添加文本

标签 linux bash awk

我需要在每一列之前添加不同的文本,我正在使用这个命令:

top -b -n1  | tail -n +8 | grep -v top | head -6 | awk 'BEGIN { OFS = "\t" } $1 = "pid=" $1, $2 = "user=" $2' | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }'

这行得通,但如果我添加另一列:

top -b -n1  | tail -n +8 | grep -v top | head -6 | awk 'BEGIN { OFS = "\t" } $1 = "pid=" $1, $2 = "user=" $2, $9 = "cpu=" $9' | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }'

我得到一个错误:

awk: linea com.:1: BEGIN { OFS = "\t" } $1 = "pid=" $1, $2 = "user=" $2, $9 = "%cpu=" $9 awk: linea com.:1:                                 ^ syntax error

语法错误在“$2”之后的“,”上。

我不明白为什么。命令的完整输出(没有在每列前添加文本)例如:

2015-05-31 11:16:08 1589 root 12,4 2,2 Xorg

2015-05-31 11:16:08 3 root 6,2 0,0 ksoftirqd/0

2015-05-31 11:16:08 1 root 0,0 0,1 init

2015-05-31 11:16:08 2 root 0,0 0,0 kthreadd

2015-05-31 11:16:08 5 root 0,0 0,0 kworker/0:0H

2015-05-31 11:16:08 7 root 0,0 0,0 rcu_sched

我需要这样的结果:

2015-05-31 11:16:08 1589 root 12,4 2,2 Xorg

2015-05-31 11:16:08 pid=3 user=root %cpu=6,2 %mem=0,0 command=ksoftirqd/0

2015-05-31 11:16:08 pid=1 user=root %cpu=0,0 %mem=0,1 command=init

2015-05-31 11:16:08 pid=2 user=root %cpu=0,0 %mem=0,0 command=kthreadd

2015-05-31 11:16:08 pid=5 user=root %cpu=0,0 %mem=0,0 command=kworker/0:0H

2015-05-31 11:16:08 pid=7 user=root %cpu=0,0 %mem=0,0 command=rcu_sched

直到专栏用户它才有效。有人能帮助我吗? 非常感谢

最佳答案

The syntax error is on "," after "$2". I don't understand why.

因为出现在同一行的多个命令需要用 ; 分隔,而不是 ,。 (看看手册会有帮助)

但是,您目前正在使用大量工具来完成使用 awk 即可轻松完成的任务。您可以为此使用单个 awk 命令:

top -b -n1 |\
  awk 'NR>7&&!/top/&&c++<6{$1= "pid=" $1;$2= "user=" $2;print strftime("%Y-%m-%d %H:%M:%S"), $0}' OFS='\t'

更好地解释为多行脚本:

    NR>7           # Skip the first 7 lines     
&&  !/top/         # Skip lines containing the term 'top'
&&  c++<6   {      # Limit output to 6 lines

    $1= "pid=" $1  # Fix pid field
    $2= "user=" $2 # Fix user fields

    # Print the modified line with a timestamp in front of it
    print strftime("%Y-%m-%d %H:%M:%S"), $0
}

关于linux - AWK,在每列奇怪的行为之前添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555804/

相关文章:

linux - 环境变量地址的随机化

linux - 在 bash 中按日期字段对日志进行排序

linux - 在串行端口上启用内核低级调试

linux - 内存错误 JVM 启动我的世界服务器

bash - 在命令行中找到了 FFMpeg 尾随选项

linux - 如何打印特定用户的UID、GID?

linux - 使用 awk 解析在字段中包含逗号的制表符分隔文件

vim - 在关键字后添加常量

c++ - 转储内存以查找 C++ 应用程序中的内存泄漏

c - 一个共享内存段是否有可能多次附加到同一个父 pid?