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

时间:2023-01-23 17:34:26

Please can you tell me how I can iterate through each of the rows found in the output of ps axo %mem,pid,euser,cmd | sort -nr | head -n 10 so that new output contains the string "new_line" at the end of each row?

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

I tried the following, but it does not always output all of the data depending on the amount of content in the row:

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

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

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

Current Output:

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 

Expected Output (instead of the spaces, there would be a '|'):

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

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

Thanks, Max.

1 个解决方案

#1


1  

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

#1


1  

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