Albinoswordfish
Albinoswordfish

Reputation: 1957

UNIX BASH: extracting number from string

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.

Upvotes: 3

Views: 15780

Answers (6)

Dennis Williamson
Dennis Williamson

Reputation: 360085

Pure Bash:

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

Or:

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

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 342363

Shell, no need to call external tools

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

Upvotes: 3

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

Pure Bash:

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

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

pid=${BASH_REMATCH[1]}

Upvotes: 2

Peter Tillemans
Peter Tillemans

Reputation: 35341

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.

Upvotes: 11

Sean
Sean

Reputation: 29772

I think this is what you want:

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

Upvotes: 2

CrayonViolent
CrayonViolent

Reputation: 32532

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

Upvotes: 1

Related Questions