我需要在每一列之前添加不同的文本,我正在使用这个命令:
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/