deepaklearner
deepaklearner

Reputation: 161

Count number of files using unix

How can we count the number of files present in a directory at server using unix in mainframe environment. I have tried the following commands but it abending with error mentioned at bottom:

cd "/Deepak/dir"

ls -1 | wc -l
ls -l . | egrep -c '^-'
ls -cf    

After trying first command, the error message I am getting is: Can't ls: "/Deepak/dir/|" not found.

I don't know why pipe is shown here. And I think that is the reason, error is saying directory is not found as "/Deepak/dir/|" and "/Deepak/dir/" are not same.

Upvotes: 0

Views: 309

Answers (4)

Arunjith
Arunjith

Reputation: 9

ls | wc -l will also work fine

Upvotes: 1

Digital Trauma
Digital Trauma

Reputation: 15996

If you want files only AND you only want to count files with newlines in their names once, then this should be a reasonably safe method:

i=0
while read -d ''; do
    ((i++))
done < <( find /Deepak/dir -maxdepth 1 -type f -print0 )
echo $i

Caveat: The GNU version of find found in most distros is subtly different to the find, which is probably more likely found in "Unix". The above works for me with both versions (e.g. on Linux and OSX). But your may have yet another different version of find.

Upvotes: 0

gts
gts

Reputation: 627

If you want only files and not (sub)directories to be counted in the directory you are checking use the following instead of ls -1

find yourdirname -maxdepth 1 -type f | wc -l

-maxdepth limits find to yourdirname only and -type f takes into account files only when searching.

Upvotes: 0

snollygolly
snollygolly

Reputation: 1886

How about:

ls -1 | wc -l

This appears to work for me.

Upvotes: 2

Related Questions