UNIX BASH: extracting number from string

15,670

Solution 1

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.

Solution 2

Shell, no need to call external tools

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

Solution 3

Pure Bash:

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

Or:

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

Solution 4

I think this is what you want:

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

Solution 5

Pure Bash:

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

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

pid=${BASH_REMATCH[1]}
Share:
15,670
Albinoswordfish
Author by

Albinoswordfish

Updated on July 13, 2022

Comments

  • Albinoswordfish
    Albinoswordfish almost 2 years

    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.