问题描述
我经常将grep与find一起使用两次,以便在文件中搜索以下两种模式:
I often use grep twice with find in order to search for two patterns in a file as follows:
find . -name \*.xml | xargs grep -l "<beans" | xargs grep singleton
然后我碰到了带有空格的文件,这些文件当然破坏了上面的命令.我对它进行了如下修改以处理空格:
Then I ran into files with spaces which of course broke the above command. I modified it as follows to deal with the spaces:
find . -name \*.xml -print0 | xargs -0 grep -l "<beans" | xargs grep singleton
-print0选项告诉find使用print null作为分隔符而不是空格,而-0选项告诉xargs期望为null.只要我要查找的文件的路径中都没有空格,该方法就可以工作,但是如果有的话,它就会中断.
The option -print0 tells find to use print null as a separator instead of space and -0 tells xargs to expect a null. This works as long as none of the files I am looking for have spaces in their paths, but it breaks if they do.
所以我需要一个标志来告诉grep以speartor而不是换行符的形式输出null.
So what I need is a flag to tell grep to print null as a speartor instead of newline.
有什么想法吗?
推荐答案
好问题.您可以使用Z选项使grep -l使用空值作为分隔符:
Good question. You can make grep -l use nulls as a delimiter with the Z option:
find . -name \*.xml -print0 | xargs -0 grep -lZ "<beans" | xargs grep singleton
您还可以使xargs作为换行符来作为分隔符.这也应该起作用:
You can also make xargs us the newline character as a delimiter. That should work for too:
find . -name \*.xml -print0 | xargs -0 grep -l "<beans" | xargs "--delimiter=\n" grep singleton
第一个解决方案更好.
这篇关于在文件名中查找空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!