The script I have receives arguments and needs to grep through another file. Script loops through every argument.

Is there a way to collect the arguments in a single search string and grep with OR ? I'd like to do this to improve the speed hoping that searching everything at once will make my script faster. Appreciate any ideas.

  • I'm sorry, i just love the title to this question. – 111--- Aug 4 '15 at 20:09

egrep (or grep -E) can do OR:

egrep "string|string|string" <file>
  • yes, does this goes over the file once or thrice ? – user2980702 Aug 4 '15 at 18:29
  • 2
    One time. This solution uses extended regex feature of modern grep binaries. Historically egrep and grep were separate binaries. – h3rrmiller Aug 4 '15 at 18:34
  • I'm having an issue with getting a string of all the arguments. How would I print out all the arguments with "|" in between ? – user2980702 Aug 4 '15 at 18:41
  • 2
    echo "string string string" | tr " " "|" – h3rrmiller Aug 4 '15 at 18:43
grep -e foo -e bar -e baz files


grep 'foo
baz' files

If those foo, bar, baz are meant to be strings as opposed to basic regular expressions, add the -F option to those 2 grep commands above.

For extended regular expressions:

grep -E 'foo|bar|baz' files

If the list of strings is in the positional parameters ($1, $2...):

IFS=$NL  # or IFS=$'\n' with ksh93/zsh/bash/mksh/FreeBSD sh...
grep -Fe "$*" files

($* is the concatenation of the positional parameters with the first character of $IFS)

  • I guess we both saw the same thing. I just deleted mine, but could you mention grep '' or -E '||', or grep "$NL" please? – mikeserv Aug 4 '15 at 19:51
  • @mikeserv, the empty string is found in every string, that's why including the empty string in the list of searches will match every line. Not sure it's worth mentioning here. – Stéphane Chazelas Aug 4 '15 at 19:53
  • Well, yeah, I get that, and you have a point. The only reason I considered it worth doing so was that elsewhere echo "string string string" | tr " " "|" is recommended, which would be problematic given an argument like fn ' *' - if you take my meaning - (even if that would be a syntax error as written for Eregexp). – mikeserv Aug 4 '15 at 19:56
  • keep it simple, grep -E 'foo|ba[rz]' files – Avinash Raj Aug 5 '15 at 5:13

An alternative would be using ack which supports extended regex by default:

ack "one|two"

For case insensitivity use ack -i and for non-standard filetypes use ack --all.

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.