0

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.

1
  • the simplest grep function you need is grep -o ".*INFO\|Param : [0-9]*" Commented Jun 5, 2013 at 10:56

2 Answers 2

2
grep -o ".*INFO\|Param : [0-9]*"
Sign up to request clarification or add additional context in comments.

Comments

1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.