tags:

views:

81

answers:

6

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  A: 

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

Crayon Violent
what if its not 4 digits?
ghostdog74
Then OP should be more specific
Crayon Violent
It's safe to assume that "pid" implies 1-5 digits (on many systems).
Dennis Williamson
+2  A: 

I think this is what you want:

pid=$(echo $str | sed 's/^\([0-9]\{4\}\).*/\1/')
Sean
I choose this answer because it stuck with using the sed command :p
Albinoswordfish
+4  A: 

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.

Peter Tillemans
+1 In this context, awk is perfect for the job
Helper Method
+2  A: 

Pure Bash:

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

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

pid=${BASH_REMATCH[1]}
fgm
+2  A: 

Shell, no need to call external tools

$ s="8962 ? 00:01:09 java"
$ IFS="?"
$ set -- $s
$ echo $1
8962
ghostdog74
No need to set `IFS="?"` since `set -- $s` will break on spaces.
Dennis Williamson
+2  A: 

Pure Bash:

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

Or:

string='8962 ? 00:01:09 java'
array=($string)
pid=${array[0]}
Dennis Williamson
You forgot `pid=${string%% *}`.
Mark Edgar
@Mark: True. And you forgot `pid=${string/ *}` ;-)
Dennis Williamson