SegFault
SegFault

Reputation: 2220

Get numbers from line and separate them in bash

I have this line:

io=9839.1MB, bw=4012.3KB/s, iops=250, runt=2511369msec

and I need to extract the numbers, to get an output like this:

9839.1 4012.3 250 2511369

I tried with sed 's/[^0-9.]*//g' but numbers are not separated from each other.

How can I do that?

Upvotes: 1

Views: 287

Answers (4)

Benjamin W.
Benjamin W.

Reputation: 52506

With shell parameter expansion:

$ var='io=9839.1MB, bw=4012.3KB/s, iops=250, runt=2511369msec'
$ echo "${var//[![:digit:]. ]}"
9839.1 4012.3 250 2511369

Specifically, this uses the ${parameter//pattern/string} with an empty string and a negated bracket expression for pattern: [![:digit:]. ] – everything other than digits, periods and spaces.

Upvotes: 0

Mirko
Mirko

Reputation: 1042

The Fish

    // a group containing a digit and the literal character "." at least once
    const regex = /([\d.]+)/g
    // your string
    const haystack = `io=9839.1MB, bw=4012.3KB/s, iops=250, runt=2511369msec`
   
    console.log(haystack.match(regex))

How to fish: Here is the fantastic regex101 featuring a wysiwyg regexp editor including a large knowledge base. https://regex101.com/r/a2scnd/1

Upvotes: 0

Inian
Inian

Reputation: 85875

Your attempt with sed is almost right, just need a add a single whitespace character for excluding from replacement,

sed 's/[^0-9. ]*//g' file
9839.1 4012.3 250 2511369

You can also use GNU grep with a -E regular expression syntax and -o for matching only words which include digits and dots.

grep -o -E '[0-9.]+' file
9839.1
4012.3
250
2511369

Upvotes: 1

Cyrus
Cyrus

Reputation: 88939

Remove everything but digits, dots and blanks:

echo 'io=9839.1MB, bw=4012.3KB/s, iops=250, runt=2511369msec' | tr -cd '0-9. '

Output:

9839.1 4012.3 250 2511369

Upvotes: 2

Related Questions