0

I would like to apply the print only-matching option (-o) to one pattern specified by grep -e 'PATTERN' syntax, while another similarly specified pattern should display the whole line containing the match (i.e. default behavior). Can this be done?

  • 1
    Enclose one pattern between anchors ^.* and .*$. – jimmij Feb 28 at 17:03
  • @jimmij, @nasir-riley while this would solve this particular instance of the problem, it doesnt seem to generalize to the situation described in the question title, e.g. if you would like to --invert-match one expression while print --only-matching another? – nils-holmberg Feb 28 at 18:20
4

This will select only the matches for one pattern and the full line for another:

grep -oe 'this_pattern' -e '^.*that_pattern.*$' file

This also works and makes it a bit cleaner:

grep -Eoe 'this_pattern|^.*that_pattern.*$' file
2

Not today.

The current source code for GNU grep indicates a global "only_matching" variable which is toggled on by the -o option. That variable is used during the printing process to determine how much of the line to print.

  • tried to upvote this as useful, but apparently need to improve my rep first :) – nils-holmberg Feb 28 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.