遍历awk中的行并追加字符串

时间:2013-05-11 15:45:06

标签: linux sorting awk ps

请告诉我如何遍历ps axo %mem,pid,euser,cmd | sort -nr | head -n 10输出中的每一行,以便新输出在每行末尾包含字符串“new_line”?

我尝试了以下操作,但它并不总是输出所有数据,具体取决于行中的内容量:

ps axo %mem,pid,euser,cmd | sort -nr | head -n 10 | awk '{print $1"|"$2"|"$3"|"$4"|"$5" new_line "}'

当前输出:

15.9|1077|git|sidekiq|2.7.5 new_line 
14.0|878|git|unicorn_rails|master new_line 
13.3|1090|git|unicorn_rails|worker[1] new_line 
13.3|1088|git|unicorn_rails|worker[0] new_line 
3.9|716|mysql|/usr/sbin/mysqld| new_line 
1.2|3412|max|-bash| new_line 
1.1|919|root|/usr/bin/python|/usr/bin/fail2ban-server new_line 
1.0|746|www-data|php-fpm:|pool new_line 
1.0|745|www-data|php-fpm:|pool new_line 
1.0|744|www-data|php-fpm:|pool new_line 

预期输出(而不是空格,会有'|'):

15.8  1077 git      sidekiq 2.7.5 gitlab [0 of 25 busy] new_line                                                                                                                                                              
14.0   878 git      unicorn_rails master -c /home/git/gitlab/config/unicorn.rb -E production new_line                                            
13.3  1090 git      unicorn_rails worker[1] -c /home/git/gitlab/config/unicorn.rb -E production new_line                                         
13.3  1088 git      unicorn_rails worker[0] -c /home/git/gitlab/config/unicorn.rb -E production new_line
 3.9   716 mysql    /usr/sbin/mysqld new_line
 1.2  3412 max      -bash new_line
 1.1   919 root     /usr/bin/python /usr/bin/fail2ban-server -b -s /var/run/fail2ban/fail2ban.sock new_line
 1.0   746 www-data php-fpm: pool www new_line                                        
 1.0   745 www-data php-fpm: pool www new_line                                        
 1.0   744 www-data php-fpm: pool www new_line

谢谢, 最大

1 个答案:

答案 0 :(得分:1)

$ ps axo %mem,pid,euser,cmd \
  | sort -nr \
  | awk -v OFS="|" '{$1=$1; print $0 " newline"} NR==10{exit}'