UNIX BASH: extracting number from string
This is probably a very simple question to an experienced person with UN开发者_C百科IX 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.
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.
Shell, no need to call external tools
$ s="8962 ? 00:01:09 java"
$ IFS="?"
$ set -- $s
$ echo $1
8962
Pure Bash:
string='8962 ? 00:01:09 java'
pid=${string% \?*}
Or:
string='8962 ? 00:01:09 java'
array=($string)
pid=${array[0]}
I think this is what you want:
pid=$(echo $str | sed 's/^\([0-9]\{4\}\).*/\1/')
Pure Bash:
string="8962 ? 00:01:09 java"
[[ $string =~ ^([[:digit:]]{4}) ]]
pid=${BASH_REMATCH[1]}
/^[0-9]{4}/
matches 4 digits at the beginning of the string
精彩评论