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.
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.
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.
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.
Three types of regexThe grep understands three different types of regular expression syntax as follows: basic (BRE) extended (ERE) perl (PCRE)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With