1

Linux and Unix-like shells like bash allow for the use of globs to approximate filenames and make file searching easier. I'm aware of the wildcard glob (*). What other globs exist in bash that I can make use of with grep?

  • 2
    grep uses regular expressions; these are different than globs. Some grep implementations use globs with options like --exclude=GLOB but I think these options are not required by POSIX. So you shouldn't assume grep knows anything about globs. – Kamil Maciorowski Sep 18 '18 at 22:09
  • @KamilMaciorowski I'm aware of the difference between globs and regex, but I was under the impression that GNU grep supports globs by default (even with grep -F) just like most other commands in bash. – Hashim Sep 18 '18 at 22:11
  • 3
    "just like most other commands in bash" – grep is not a "command in bash" but a separate executable that you can run without a shell, if you know how. You should carefully distinguish globs expanded by bash before grep (or any command invoked in a shell) even runs from globs, regular expressions or anything alike that is supported by the command itself. – Kamil Maciorowski Sep 18 '18 at 22:16
  • 2
    The shell will expand globs before passing them to grep in the argument list. Thus, grep -f *.txt will expand to something like grep -f file1.txt file2.txt file3.txt, and grep will interpret file1.txt as the file to read search patterns from, and file2.txt and file3.txt as files to search for those patterns. grep has no idea whatsoever that there was a glob pattern involved, it only knows that it got the strings "-f", "file1.txt", "file2.txt", and "file3.txt" as arguments. – Gordon Davisson Sep 19 '18 at 2:09
  • 1
    Invoke set -x (use set +x to revert this later). Then run grep -f *.txt 1>/dev/null 2>/dev/null (redirections are just to make the command itself silent). Whatever you see after + is the actual command. Try it in directories with 0, 1 or more matching files. You will see what arguments grep really gets. – Kamil Maciorowski Sep 19 '18 at 6:44

Your Answer

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

Browse other questions tagged or ask your own question.