Search predicate grouping

This part of "(-name * txt -o -name * html)" confuses me in the code:

find $HOME \( -name \*txt -o -name \*html \) -print0 | xargs -0 grep -li vpn 

Can someone explain the brackets and the "-o"? Is "-o" a command or parameter? I know that the brackets are escaped "\", but why are they needed?

+4
source share
3 answers

By default, the conditions in the argument list find "and" together. The -o option means "or."

If you wrote:

 find $HOME -name \*txt -o -name \*html -print0 

then there is no output action associated with ending the file names with "txt", so they will not be printed. By grouping the name parameters with parentheses, you get the "html" and "txt" files.


Consider an example:

 mkdir test-find cd test-find cp /dev/null file.txt cp /dev/null file.html 

There is an interesting side light in the comments below. If the team was:

 find . -name '*.txt' -o -name '*.html' 

then, since no explicit action is specified for any alternative, the default value of -print (not -print0 !) is used for both alternatives, and both files are listed. Using -print or another explicit action after one of the alternatives (but not the other), then only the alternative with the action is valid.

 find . -name '*.txt' -print -o -name '*.html' 

It also suggests that you may have different actions for different alternatives. You can also apply other conditions, such as modification time:

 find . \( -name '*.txt' -o -name '*.html' \) -mtime +5 -print0 find . \( -name '*.txt' -mtime +5 -o -name '*.html' \) -print0 

The first prints txt or html files older than 5 days (so that it does not print anything for the examples directory - the files take several seconds); the second prints txt files older than 5 days or html files of any age (so just file.html). And so on...

Thanks to DevSolar for his comments leading to this addition.

+6
source

"-o" means OR. Ie, the name must end with "txt" or "html". The brackets simply group the two conditions together.

+3
source

(and) provide a way to group search parameters for the find command. -o is the "or" operator.

This find command will find all files ending in "txt" or "html" and pass them as arguments to grep.

+2
source

All Articles