How to extract substring and numbers only with grep / sed

I have a text file containing both text and numbers, I want to use grep to extract only the numbers that I need, for example, for a file:

miss rate 0.21  
ipc 222  
stalls n shdmem 112

So say that I only want to extract data for miss ratewhich 0.21. How to do it with grep or sed? In addition, I need more than one number, not just after miss rate. That is, I might want to get both 0.21, and so 112. An example output might look like this:

0.21 222 112

Because I need data for the next chart.

+5
source share
6 answers

Use instead awk:

awk '/^miss rate/ { print $3 }' yourfile

grep, , , GNU grep PCRE (-P) lookbehind (? < =..) (-o):

grep -Po '(?<=miss rate ).*' yourfile
+3

regex \K :

grep -oP 'miss rate \K.*' file.txt

:

perl -lne 'print $& if /miss rate \K.*/' file.txt
+4

grep -and- cut :

3- grep:

grep "^miss rate " yourfile | cut -d ' ' -f 3

, :

grep "^miss rate " yourfile | cut -d ' ' -f 3-

, bash "miss rate" , :

a=( $(grep -m 1 "miss rate" yourfile) )
echo ${a[2]}

${a[2]} - .

" " , grep, , . ( bash)

+4

grep , :

grep "miss rate" file | grep -oe '\([0-9.]*\)'

First, it will find a string that matches, and then it will only output numbers.

Sed might be a bit more readable:

sed -n 's#miss rate ##p' file
+1
source

You can use:

grep -P "miss rate \d+(\.\d+)?" file.txt

or

grep -E "miss rate [0-9]+(\.[0-9]+)?"

Both of these commands print miss rate 0.21. If you want to extract only the number, why not use Perl, Sed or Awk?

If you really want to avoid this, maybe this will work?

grep -E "miss rate [0-9]+(\.[0-9]+)?" g | xargs basename | tail -n 1
0
source

I believe

sed 's|[^0-9]*\([0-9\.]*\)|\1 |g' fiilename

will do the trick. However, each entry will be on its own line if this is normal. I'm sure sed has the ability to create a list with a comma or space, but I'm not the supermaster of all things sed.

0
source

All Articles