Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

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

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
share|improve this answer

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

grep -lR ^ . | grep -c ^
share|improve this answer
Does not count empty files; my answer matches them neither. – kubanczyk Jan 17 '12 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" – olibre Jan 17 '12 at 16:44
Yup. Your grep -c fits the requirement much better, that's why I've upvoted it :) – kubanczyk Jan 17 '12 at 16:54
@kubanczyk Your answer is more pedagogical ;-) What a pity Marios does not respond :-( – olibre Jan 17 '12 at 21:51
Please @Marios can you check the answers? – olibre Jan 18 '12 at 21:12
du -ah | wc -l

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

Your Answer


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.