Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm using Mac 10.7.5 and on a bash shell. I'm trying to find instances of a string in a group of files but keep getting this error

Daves-MacBook-Pro:folder davea$ find . -name "*" | xargs grep 'state-icons'
xargs: grep: Argument list too long

How can I run the command (or a similar one) to avoid this error?

share|improve this question
    
grep '...' <( find … ) maybe? –  slhck Aug 6 '13 at 16:58
add comment

1 Answer

up vote 1 down vote accepted

You can use the -n option of xargs to limit the number of arguments.

find . -name "*" | xargs -n 20 grep 'state-icons'

Note that it does not work for files with whitespace in their names.

share|improve this answer
2  
It works for files with spaces in their names. It fails only for files with newlines in their names, which are much rarer. –  rici Aug 6 '13 at 15:23
    
Would limiting the number of arguments potentially prevent the correct results from being displayed? Ultimately my goal is to find files with an instance of the desired string, as opposed to simply eliminating the error message. –  Dave Aug 6 '13 at 15:24
    
@Dave: No, grep will be run several times, with 20 file arguments each. You might add -type f to find to avoid errors when grep tries to open directories. –  choroba Aug 6 '13 at 15:27
    
There’s a risk that if the find reports, say, 61 files, then xargs will run grep four times –– three times with 20 files and once with 1 file. When grep is run with multiple files, it reports the name(s) of the file(s) where it finds matches; not so with only one filename argument. A trick that is commonly used to fix this is to say xargs -n 20 grep 'state-icons' /dev/null, so xargs will run grep three times with 21 files and once with 2 files –– the additional file, of course, being /dev/null, which will otherwise have no effect on the run. –  Scott Aug 6 '13 at 15:49
2  
@Scott: You can also use the -H option of grep (if supported). –  choroba Aug 6 '13 at 16:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.