How can I count all files without using find and only grep? I tried using ls recursively but how can I pipe that to grep and count files?

link|improve this question
7  
Why do you refuse to use find? Parsing the ls output is bad. – grawity Jan 17 at 12:40
feedback

3 Answers

To list all files that match a grep pattern:

grep -rl your_regex_pattern /my/dir /my/other_dir /my/file

To count them:

grep -rl your_regex_pattern /my/dir /my/other_dir /my/file  | wc -l

To count all non-empty files in a directory recursively, you search for an empty string (two single quotes):

grep -rl '' /my/dir       | wc -l
link|improve this answer
feedback

If you really want to use solely grep therefore you can do:

grep -lR ^ . | grep -c ^
link|improve this answer
Does not count empty files; my answer matches them neither. – kubanczyk Jan 17 at 14:41
Yes @kubanczyk your answer (grep -rl '' /my/dir) is the same as mine (grep -lR ^ /my/dir): the two answers ignore empty files :-( Let's say this is a feature ;-) Maybe @Marios do not want to count the empty files... NB: he said "only grep" – oHessling Jan 17 at 16:44
Yup. Your grep -c fits the requirement much better, that's why I've upvoted it :) – kubanczyk Jan 17 at 16:54
@kubanczyk Your answer is more pedagogical ;-) What a pity Marios does not respond :-( – oHessling Jan 17 at 21:51
Please @Marios can you check the answers? – oHessling Jan 18 at 21:12
feedback
du -h | wc -l

[and then subtract 1]

*edit: du -ah | wc -l

link|improve this answer
du -h lists directories only, not files. – haimg Jan 17 at 23:04
Fine, du -ah | wc -l – Noxville Jan 20 at 9:08
Afaik, this prints the same file only once, I.e. ignores additional hard links. – Daniel Beck Jan 20 at 10:16
feedback

Your Answer

 
or
required, but never shown

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