Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract substring and numbers only using grep/sed

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

miss rate 0.21  
ipc 222  
stalls n shdmem 112

So say I only want to extract the data for miss rate which is 0.21. How do I do it with grep or sed? Plus, I need more than one number, not only the one after miss rate. That is, I may want to get both 0.21 and 112. A sample output might look like this:

0.21 222 112

Cause I need the data for later plot.

like image 660
Hooloovoo Avatar asked Mar 12 '13 20:03

Hooloovoo


People also ask

Can we use grep with sed?

Using sed as grep. By default, sed will print every line it is scanning to the standard output stream. To disable this automatic printing, we can use the flag -n. Next, it will run the script that comes after the flag -n and look for the regex pattern ERROR on every line in log.

What is the difference between sed and grep?

The Differences Between Grep, sed, and AWK Grep is used for finding text patterns in a file and is the simplest of the three. Sed can find and modify data, however, its syntax is a bit more complex than grep.

How do you grep multiple things?

The basic grep syntax when searching multiple patterns in a file includes using the grep command followed by strings and the name of the file or its path. The patterns need to be enclosed using single quotes and separated by the pipe symbol. Use the backslash before pipe | for regular expressions.

Does grep regex?

Three types of regexThe grep understands three different types of regular expression syntax as follows: basic (BRE) extended (ERE) perl (PCRE)


1 Answers

If you really want to use only grep for this, then you can try:

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

It will first find the line that matches, and then only output the digits.

Sed might be a bit more readable, though:

sed -n 's#miss rate ##p' file
like image 193
DanneJ Avatar answered Sep 17 '22 11:09

DanneJ