I need to find lines in the text file that have at least one x and at least two ys.

I tried the following:

grep -E "x.*y{2}" file.txt

This method did not work. Is there another way to do it?

  • So what is your question? – cuonglm Sep 19 '14 at 16:07
  • Does it need to be grep? – terdon Sep 19 '14 at 16:11
  • Yes, it needs to be grep. – Elijah Sep 19 '14 at 16:13
  • And you need it to match any of x blah y blah y or y blah x blah y or y blah y blah x? I mean, can they be in any order? And why does it need to be done in a single grep call? – terdon Sep 19 '14 at 16:14
  • The ordering does not matter. I was looking for different variations, in particular with one regular expression. – Elijah Sep 19 '14 at 16:17

You can use two consecutive grep calls:

grep 'x' file.txt | grep 'y.*y'

or one with the three possibilities:

grep -E 'x.*y.*y|y.*x.*y|y.*y.*x' file.txt
  • It has to be one regular expression. – Elijah Sep 19 '14 at 16:10
  • @Elijah I modified my answer. Please be more specific in future questions. – jofel Sep 19 '14 at 16:15
  • Sorry, my bad. I did not specify the pattern I was looking for. – Elijah Sep 19 '14 at 16:28

If they can be found in any order, I doubt you can get anything shorter than @jofel's answer. If you can use other tools, here are some options:

  1. perl

    perl -pe ' /x/ && /y.*y/ || next' file
  2. awk

    awk '/x/ && /y.*y/' file

Anything else I can think of would have to use the three-pronged approach of @jofel.

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.