UNIX BASH: extract a number from a string

This is probably a very simple question for an experienced person with UNIX, however I am trying to extract a number from a string and continue to get the wrong result.

This is the line:

8962 ? 00:01:09 java

This is the result I want

8962

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

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

If anyone can help me, this will be appreciated.

+3
source share
6 answers

There are several ways to throw 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 a string in different fields based on ranges of divides or just bytes and is often useful in these tasks.

awk is an older programming language that is especially useful for working with one line at a time.

+11

Shell,

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

Pure Bash:

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

:

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

, , :

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

Pure Bash:

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

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

pid=${BASH_REMATCH[1]}
+2
source

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

+1
source

Source: https://habr.com/ru/post/1761588/


All Articles