grouping predicates in find

孤街浪徒 提交于 2019-12-19 03:20:58

问题


This part " ( -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 the brackets and "-o"? Is "-o" a command or a parameter? I know the brackets are escaped by "\" , but why are they for?


回答1:


By default, the conditions in the find argument list are 'and'ed 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 the file names end with 'txt', so they would not be printed. By grouping the name options with parentheses, you get both the 'html' and 'txt' files.


Consider the example:

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

The comments below have an interesting side-light on this. If the command was:

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

then, since no explicit action is specified for either alternative, the default -print (not -print0!) action is used for both alternatives and both files are listed. With a -print or other explicit action after one of the alternatives (but not the other), then only the alternative with the action takes effect.

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

This also suggests that you could have different actions for the different alternatives. You could also apply other conditions, such as a 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 it prints nothing for the example directory - the files are a few seconds old); 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.




回答2:


The "-o" means OR. I.e., name must end in "txt" or "html". The brackets just group the two conditions together.




回答3:


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

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



来源:https://stackoverflow.com/questions/637467/grouping-predicates-in-find

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!