0

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.

1

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.

0

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
0

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 }'

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.