1

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?

2
  • 1
    Enclose one pattern between anchors ^.* and .*$.
    – jimmij
    Commented Feb 28, 2019 at 17:03
  • 1
    @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? Commented Feb 28, 2019 at 18:20

2 Answers 2

5

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
3

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.

1
  • tried to upvote this as useful, but apparently need to improve my rep first :) Commented Feb 28, 2019 at 18:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .