543

To count the number of files in a directory, I typically use

ls directory | wc -l

But is there another command that doesn't use wc ?

11
  • 28
    What exactly is the problem with wc that prevents you from using it? Commented Jan 3, 2014 at 2:04
  • 6
    Not really. Unix commands are generally intended to be used this way, chained in pipes. Commented Jan 3, 2014 at 2:04
  • 4
    I am connecting via ssh to another host to access some data . Unfortunately a bunch of basic commands don't seem to work on this host . If I use wc it returns "unrecognized command" . So I am looking for other options . Commented Jan 3, 2014 at 2:25
  • 11
    Use the tree command. It will give you the tree and at the bottom tell you how many files and directories there are. If you want hidden files also use tree -a. Commented Mar 3, 2015 at 21:20
  • 10
    @vanza "What exactly is the problem with wc" , what if a file has a \n in the file name? Yes, extremely unlikely! But still technically valid and possible. Commented Jun 26, 2015 at 5:57

1 Answer 1

829

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

Sign up to request clarification or add additional context in comments.

17 Comments

No wait . I made a booboo . You are absolutely right Sajad Lfc . ls -1 dir | egrep -c '' This returns the number of files in dir . Thanks .
@runios that's because ls -l returns an additional line at the top adding up the file sizes for a total amount. You should use ls -1 and not the ls -l. Also if one wants hidden files but without the directories . and .. you should use ls -1A | wc -l
A weird favourite of mine: find . -type f -printf "." | wc -c
The period in the quotes after -printf is an arbitrary (ideally 1-byte) character, correct?
Quite! That's correct
An effective native way without using pipe: du --inodes [root@cs-1-server-01 million]# du --inodes 1000001 ./vdb.1_1.dir 1000003 . [root@cs-1-server-01 million]#
Isn't this one against the tradition of not parsing ls?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.