Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: how to get total numbers of files in a directory?

by gjb (Vicar)
on Dec 09, 2003 at 13:51 UTC ( #313410=note: print w/replies, xml ) Need Help??

in reply to how to get total numbers of files in a directory?

Since you seem to work on a Un*x system you could also simply resort to command line tools that are quite up to this task. (That is, if you're only after the result of what you ask about.)

find /home/a -type f -name "*.txt" | wc -l
would do nicely, although it would count recursively, i.e. it would also count text files in subdirectories. If you want to limit the count to the specified directory, modify the above to read:
find /home/a -type f -name "*.txt" -maxdepth 0 | wc -l

The /home/a is the directory you want to search, -type f specifies that you're only interested in files, -name "*.txt" implies that you only want files that have a .txt suffix, -maxdepth 0 specifies that you want 0 levels of recursion, i.e. you want find to limit itself to the directory specified.

Learning how to use find definitely pays off, see the relevant man page for more info since it is really very powerful, especially when using the -exec flag.

Hope this helps, -gjb-

Replies are listed 'Best First'.
Re: Re: how to get total numbers of files in a directory?
by Hena (Friar) on Dec 09, 2003 at 14:03 UTC
    Easier method for one directory is ofcourse
    ls /home/a/*.txt |wc -l
    But learning find is definedly worth it as well :).

    Duh, was *.txt. Double duh, ls goes wild if dir name matches as well, so be careful. Find tends to be easier to keep under control :P.
      to avoid ls wildness and to get a true listing of all files ( some versions of ls, like hp-ux, put multiple files on one line ) do ls -ald /home/a/*.txt | wc -l And Find is also your Friend.
Re: Re: how to get total numbers of files in a directory?
by waswas-fng (Curate) on Dec 09, 2003 at 17:46 UTC
    -maxdepth is not implemented on all versions of find. beware. a suitable replacement for getting the number of *.txt files in the current directory is  ls | egrep '\.txt$' |wc -l with the caveat that directory names that end in .txt will be falsely listed in the count.

      This would miss hidden files. Maybe ls -lad *.txt | grep -v ^d | wc -l would be a better solution.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://313410]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (9)
As of 2018-04-21 12:18 GMT
Find Nodes?
    Voting Booth?