spancer
spancer

Reputation: 13

get number value between two strings using regex

I have a string with multiple value outputs that looks like this:

SD performance read=1450kB/s write=872kB/s no error (0 0), ManufactorerID 27 Date 2014/2 CardType 2 Blocksize 512 Erase 0 MaxtransferRate 25000000 RWfactor 2 ReadSpeed 22222222Hz WriteSpeed 22222222Hz MaxReadCurrentVDDmin 3 MaxReadCurrentVDDmax 5 MaxWriteCurrentVDDmin 3 MaxWriteCurrentVDDmax 1

I would like to output only the read value (1450kB/s) using bash and sed. I tried

 sed 's/read=\(.*\)kB/\1/'

but that outputs read=1450kB but I only want the number. Thanks for any help.

Upvotes: 1

Views: 108

Answers (2)

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

Running

sed 's/read=\(.*\)kB/\1/'

will replace read=[digits]kB with [digit]. If you want to replace the whole string, use

sed 's/.*read=\([0-9]*\)kB.*/\1/'

instead.

As Sundeep noticed, sed doesn't support non-greedy pattern, updated for [0-9]* instead

Upvotes: 1

Sundeep
Sundeep

Reputation: 23667

Sample input shortened for demo:

$ echo 'SD performance read=1450kB/s write=872kB/s no error' | sed 's/read=\(.*\)kB/\1/'
SD performance 1450kB/s write=872/s no error

$ echo 'SD performance read=1450kB/s write=872kB/s no error' | sed 's/.*read=\(.*\)kB.*/\1/'
1450kB/s write=872

$ echo 'SD performance read=1450kB/s write=872kB/s no error' | sed 's/.*read=\([0-9]*\)kB.*/\1/'
1450
  • Since entire line has to be replaced, add .* before and after search pattern
  • * is greedy, will try to match as much as possible, so in 2nd example it can be seen that it matched even the values of write
  • Since only numbers after read= is needed, use [0-9] instead of .

Upvotes: 3

Related Questions