Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have 64 processes running that have the following string

pbs_mom -m -M 1234 -R 5678 -A foo12345 -c /var/spool/torque/mom_priv/login_config 

I need to search and extract just foo12345

  • always starts with 3 lowercase letters
  • followed by 5 digits

Here is what I am trying but I am getting the entire line in return

ps aux |grep foo| grep 'foo[0-9]\+'

How can I strip off all text except foo12345.

share|improve this question
up vote 1 down vote accepted

If your grep is GNU grep, try the -o option:

ps aux |grep foo| grep -o 'foo[0-9]\+'

From man page of GNU grep:

-o, --only-matching

Prints only the matching part of the lines.

Based on your two requirements (3 lowercase letters followed by 5 digits), this should also work:

ps aux | grep -o '[a-z]\{3\}[0-9]\{5\}'

This is more efficient as it uses one pipe less.

share|improve this answer
Ha! that worked, thanks – spuder Jan 30 '14 at 22:53

My first instinct would be to use sed like so:

ps aux | sed -n '/foo/s/.*\(foo[0-9]\{5\}\).*/\1/p'

However, since the data will be structured into a standard number of columns, you could instead use cut:

ps aux | grep foo | cut -d ' ' -f 8
share|improve this answer

If your grep is not the GNU grep, you can always use Perl:

ps aux | perl -nle '/\s+([a-z]{3}[0-9]{5})\s+/ && print $1

or awk since your fields are already whitespace-separated:

ps aux | awk '{ for(i=1;i<=NF;i++) if($i ~ /[a-z]{3}[0-9]{5}/) print $i }'
share|improve this answer

Your Answer


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.