Manolete
Manolete

Reputation: 3517

grepping multiple lines from a file

I would like to grep in order multiple lines of a file. An example of the file originalfile.txt could be:

num=12
workers not specified
length= 128
Using array element 
num= 24 
workers not specified
length= 128
Using array element 
......

I want to grep only valuable lines like all those with num and length:

num=12
length= 128
num= 24 
length= 128
......

I know how to grep for just one pattern, say num but I don't know how to do it for more than one pattern.

$ grep "num" originalfile.txt

It turns out that I have some parameters in the same line that awk does not seem to find,i.e:

.... time= 1.234 Gflop/s= 3.4556 .....

It filters the first one, but not Gflop/s. Is there a way to recursvely find on the same line?

Upvotes: 6

Views: 27502

Answers (4)

glenn jackman
glenn jackman

Reputation: 246744

You can also pass multiple patterns to grep with the -e option

grep -e num -e length

Upvotes: 4

user000001
user000001

Reputation: 33307

Use the -E option

From man grep:

-E, --extended-regexp

Interpret PATTERN as an extended regular expression (see below).

$ grep -E 'length|num' data
num=12
length= 128
num= 24 
length= 128

Update if you want to only get the numbers you can pipe to awk

grep -E 'length|num' data | awk -F'= ?' '{print $2}'

But then you can do it all in a signle awk command, and avoid grep

awk -F'= ?' '/length/||/num/{print $2}' data

Upvotes: 12

Chris Seymour
Chris Seymour

Reputation: 85765

This should do the trick:

$ grep '^\w*=' file
num=12
length= 128
num= 24 
length= 128

Explanation:

^   # Start of line
\w  # Word class, shorthand for [a-zA-Z0-9_]
*   # Quantifier (zero or more)
=   # Equals character

The + quantifier is probably better (one or more) which is part of ERE (Extended Regular Expressions) so you'd need to used egrep (grep -E). This means lines that start with an = and no variable name will not be matched.

$ egrep '^\w+=' file
num=12
length= 128
num= 24 
length= 128 

Edit:

For you secondary question found in the comments, to only print the digit value we get into fancy uses of grep:

$ grep -Po '^\w+=\s?\K\d+' file
12
128
24
128

Or use a scripting language like awk

$ awk -F'= ?' '/\w*=/{print $2}' file
12
128
24 
128

Upvotes: 3

dtorgo
dtorgo

Reputation: 2116

Grep allows for regex matching. We can use a regex match with an "or" statement to search for multiple matches.

grep 'num=\|length=' file

num=12
length= 128
num= 24 
length= 128

the | symbol means "or" in regex. Because this is bash we need to escape the | so it becomes \|

Upvotes: 3

Related Questions