Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

When using grep like so:

ps aux | grep 'processname' | awk '{print $2}'

The PIDs of processes withprocessname is returned. When using this:

ps aux | grep '^processname' | awk '{print $2}'

I'm trying to get processes which commandline start with processname, but it doesn't work.

Example processes running:

processname
other_processname

I would like to get the PID of the first option, because processname is the start of the command.

I've also tried used the -E, -e, -w flags, and they all return the same result. What's incorrect?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

^ marks the start of a line, not a field.

ps aux | grep ' processname'

will come closer, but it still might give some false positives.

Since the width of the other columns is fixed, you could also use

grep '^.\{65\}processname'

Here, ^.\{65\} is exactly 65 character from the start of the line. The exact number may vary on your system.

Since you're already using awk, this would probably be a better option:

ps aux | awk '{ if ($11 == "processname") print $2 }'

You can also reformat the output of ps to make grepping easier:

ps ax -o pid,args | grep '^[^ ]\+ processname'

The switch -o pid,args makes ps display only the PID and the command with arguments. The expression ^[^ ]\+ matches all characters from the start of the line up to the first space.

share|improve this answer
    
Could you clarify what you mean by "field"? I will clarify what I'm asking for in the post. –  hexacyanide Feb 28 '13 at 2:38
    
Field in awk's sense, e.g., $2 denotes the second field. –  Dennis Feb 28 '13 at 2:40
    
I see. The reason I originally used grep is because processname has arguments that I need to identify the process. The located PID must have the initial command processname and contain index=X somewhere in there. Looks like I can do this with an && statement. Thank you. –  hexacyanide Feb 28 '13 at 2:44
    
Is there a different between cmd and args when specified as an option? –  hexacyanide Feb 28 '13 at 3:04
1  
You're right. I mixed up cmd and comm. The latter displays the bare command. cmd and args are aliases. –  Dennis Feb 28 '13 at 3:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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