user2455083
user2455083

Reputation: 13

How do i match multiple strings of a line using grep command

I have to find and print only matched strings of a line in file using grep command.

Below is example text:

04-06-2013 INFO blah blah blah blah Param : 39 another text Ending the line.
05-06-2013 INFO blah blah allah line 2 ending here with Param : 21.

I want output to be printed as below after grep command

04-06-2013 INFO   Param : 39
04-06-2013 INFO   Param : 21

I tried grep command with -o option and regex '.*INFO'. I was successful to print both the text separately in different grep commands where as i want this in single command.

Thanks in Advance.

Upvotes: 0

Views: 1216

Answers (2)

Rinku
Rinku

Reputation: 1078

grep -o ".*INFO\|Param : [0-9]*"

Upvotes: 2

m01
m01

Reputation: 9395

I'm not sure you can do this with pure grep, as you'd need to be able to specify a regex with grouped terms, and then only print out certain regex groups rather than everything matched by the entire regex - so you'd e.g. specify (.*INFO)(.*)(Param : [0-9]*) as the regex and then only print groups 1 and 3 (assuming you start counting at 1).

You can however use sed to post-process the output for you:

% cat foo
04-06-2013 INFO blah blah blah blah Param : 39 another text Ending the line.
05-06-2013 INFO blah blah allah line 2 ending here with Param : 21.
% grep 'Param :' foo | sed 's/\(.*INFO\)\(.*\)\(Param : [0-9]*\)\(.*\)/\1 \3/'
04-06-2013 INFO Param : 39
05-06-2013 INFO Param : 21

What I'm doing above is replacing the match with just groups 1 and 3, separated by a space.

I think this question is related (possibly even a duplicate).

Upvotes: 1

Related Questions