3

This is probably a very simple question to an experienced person with UNIX however I'm trying to extract a number from a string and keep getting the wrong result.

This is the string:

8962 ? 00:01:09 java

This it the output I want

8962

But for some reason I keep getting the same exact string back. This is what I've tried

pid=$(echo $str | sed "s/[^[0-9]{4}]//g")

If anybody could help me out it would be appreciated.

1
  • What if the PID isn't four digits? Commented Aug 26, 2010 at 3:25

6 Answers 6

11

There is more than one way to skin a cat :

pti@pti-laptop:~$ echo 8962 ? 00:01:09 java | cut -d' ' -f1
8962
pti@pti-laptop:~$ echo 8962 ? 00:01:09 java | awk '{print $1}'
8962

cut cuts up a line in different fields based on a delimeter or just byte ranges and is often useful in these tasks.

awk is an older programming language especially useful for doing stuff one line at a time.

Sign up to request clarification or add additional context in comments.

Comments

3

Shell, no need to call external tools

$ s="8962 ? 00:01:09 java"
$ IFS="?"
$ set -- $s
$ echo $1
8962

1 Comment

No need to set IFS="?" since set -- $s will break on spaces.
3

Pure Bash:

string='8962 ? 00:01:09 java'
pid=${string% \?*}

Or:

string='8962 ? 00:01:09 java'
array=($string)
pid=${array[0]}

2 Comments

You forgot pid=${string%% *}.
@Mark: True. And you forgot pid=${string/ *} ;-)
2

I think this is what you want:

pid=$(echo $str | sed 's/^\([0-9]\{4\}\).*/\1/')

1 Comment

I choose this answer because it stuck with using the sed command :p
2

Pure Bash:

string="8962 ? 00:01:09 java"

[[ $string =~ ^([[:digit:]]{4}) ]]

pid=${BASH_REMATCH[1]}

Comments

1

/^[0-9]{4}/ matches 4 digits at the beginning of the string

2 Comments

Then OP should be more specific
It's safe to assume that "pid" implies 1-5 digits (on many systems).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.