Question

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?

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 "}'

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.

Was it helpful?

Solution

$ ps axo %mem,pid,euser,cmd \
  | sort -nr \
  | awk -v OFS="|" '{$1=$1; print $0 " newline"} NR==10{exit}'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top