5

So what im wanting to do is pretty basic.....but im not sure how to go about it. Lets say I have a program running, but I want to pipe the output of ps -C "ProgramXX" into a file.

Normally Running ps -C "ProgramXX" Produces something to the effect of:

PID TTY TIME            CMD
123 ?   00:00:00    Program1
142 ?   00:00:00    Program1
165 ?   00:00:00    Program1
221 ?   00:00:00    Program1

Is their any "simple" way to just get the 1st columns and 4th column (ignoring the top heading line) into a text file.

I figure you could run ps -C "Program1" >> Data.txt.....then maybe run a script to cut out the fat? This would be done in Bash btw. Maybe using grep or something.....but I wouldn't really know. This would be ran multiple times btw......so data.txt would continue to grow.

5 Answers 5

12

You can control the columns that get output by ps. Note that the exact commandline does vary between the various flavours of Linux/Unix but I believe the following will do what you want.

ps --no-headers -o pid,comm  -C "ProgramXX" >> Data.txt

The man page for ps(1) will list all of the options available to you.

1
  • This seems to be the best way, thank you.
    – user4877
    Oct 5, 2011 at 17:33
6

ps is a swiss-army-knife of functionality. You want this

ps -C "ProgramXX" -o pid=,comm=

-o controls the output columns and a trailing = indicates that you don't want a header.

If you write it this way:

ps -o comm= -o pid= | grep '^ProgramXX'

Then it should work with most ps implementations. Unfortunately, -C is a GNUism.

5

pgrep -l Program1 will give the output you want.

2

You can use cut(1) to do this, e.g.

ps -C "Program1" | cut -c1-4,20-50 | tail +1

With the character positions in the -c option of cut set to cut out the right fields. tail +1 gets everything but the first line of the output, which will trim the first line.

You could also convert it into a delimited file by adding sed into the pipeline with something like:

ps -C "Program1" | sed 's/  */,/g' | cut -d, -f1,4 | tail +1

Which will give you output with comma separated values.

2
  • But How would I redirect it, would i put >> after the cut or before.
    – user4877
    Oct 5, 2011 at 15:45
  • @Sauron: It would be after, but see Richm's answer (and my own) for how to do this a better way.
    – Sorpigal
    Oct 5, 2011 at 16:41
2

Instead of cut, I like to use awk because it can extract whitespace-delimited words without having to count blank spaces:

ps -C "Program 1" | awk '{print $1,$4}'

Note that awk would not be a good solution for output that may have a blank value in a column, or a multi-word value.

You must log in to answer this question.