简体   繁体   中英

grep --include command doesn't work in OSX Zsh

I am following the best answer on How do I find all files containing specific text on Linux? to search string in my project.

This is my command grep --include=*.rb -rnw . -e "pattern" grep --include=*.rb -rnw . -e "pattern"

Zsh tells me that zsh: no matches found: --include=*.rb

It seems that grep doesn't support --include option.

When I type grep --help , it returns

usage: grep [-abcDEFGHhIiJLlmnOoPqRSsUVvwxZ] [-A num] [-B num] [-C[num]]
    [-e pattern] [-f file] [--binary-files=value] [--color=when]
    [--context[=num]] [--directories=action] [--label] [--line-buffered]
    [--null] [pattern] [file ...]

no --include here.

Is my grep version too old? Or is there something wrong with my command?

FreeBSD/macOS grep does support the --include option (see man grep ; it's unfortunate that the command-line help ( grep -h ) doesn't list this option), but your problem is that the option argument, *.rb , is unquoted .

As a result, it is your shell , zsh , that attempts to pathname-expand --include=*.rb up front , and fails, because the current directory contains no files with names matching glob pattern *.rb .
grep never even gets to execute.

Since your intent is to pass *.rb unmodified to grep , you must quote it :

grep --include='*.rb' -rnw . -e "pattern"     

If your grep does not support --include , and you don't want to install GNU grep just for this, there are a number of portable ways to perform the same operation. Off the top of my head, try

find . -type f -name '*.rb' -exec grep -nw "pattern" /dev/null {} \;

The find command traverses the directory (like grep -r ) looking for files named *.rb (like the --include option) and the /dev/null is useful because grep shows a slightly different output format when you run it on multiple files.

This is slightly inefficient because it runs a separate grep for each file. If it's too slow, look into xargs (or use find -exec ... {} \\+ instead of ... {} \\; if your find supports that). This is a very common task; you should easily find thousands of examples.

You might also want to consider ack which is a popular and somewhat more user-friendly alternative. It is self-contained, so "installation" amounts to copying it to your $HOME/bin .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM