Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

3 Answers 3

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 at 22:53
add comment

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
add comment

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
add comment

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.