0

i want to sort the process of one user by the percentage of cpu used. I tried this

ps aux|tr -s " "|cut -f3 -d " "| sort -| grep "user" > file name

does this work?

3

ps allows you to specify the columns in the output, as well the sort order. Depending upon your requirements, an additional command may not even be needed for post-processing.

Here's a command that provides a list of the specified user's processes, sorted by their percentage of CPU utilization. (The head command is merely there to restrict the output).

[root@testvm ~]# ps -o pid,uname,pcpu,command -u root --sort=-pcpu | head
  PID USER     %CPU COMMAND
    1 root      0.5 /usr/lib/systemd/systemd --switched-root --system --deserialize 21
  664 root      0.4 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
 1226 root      0.2 sshd: root@pts/0
 1261 root      0.2 [kworker/0:0]
    9 root      0.1 [rcu_sched]
   20 root      0.1 [kworker/0:1]
  293 root      0.1 [kworker/0:1H]
  875 root      0.1 -bash
 1008 root      0.1 /usr/bin/python -Es /usr/sbin/tuned -l -P

The -o option specifies the output format here, which are the following columns: Process ID, Username, Percentage of CPU Usage, & Command.

The -u option limits ps to a specific user's processes, which in this case is root.

The --sort option defines the sorting order, which is percentage of CPU usage. The prefixed - symbol defines the sort in descending order.

2

I would consider limiting the initial retrieval to the specific user and sorting, then possibly cutting.

ps hux -u USER | sort -k3 -n

By taking this approach, the processes are already limited to the specific user. The sort is then performed against the whole retrieved process. It can then be piped through the tr and cut if desired for specific fields.

Parameters:
h : suppress the headers
u : user oriented format
x : BSD remove the tty requirement

-u USER : the specific user for whom processes should be selected. Note that this may be a list.

0

I'd do it like this:

ps aux | grep user | sort -rk3 > file_name

Read about sort -rk3 with man sort

A couple things about yours:

  • spaces are important, bash doesn't know that file name is one file, it's going to redirect output to a file called file and then wonder what to do with name. If you must put spaces in filenames, you'll have to quote them: ... > "file name".

  • Many linux apps are kind of smart about picking columns out without counting/collapsing spaces. If I wanted just the percentages I'd do this:

    ps aux | grep user | sort -rk3 | awk '{print $3}'

    cut is probably smart like that too, I'm just less familiar with it.

  • You might also consider top -bn1 | grep user which does something similar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.