简体   繁体   中英

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.

How about:

ls -1 | wc -l

This appears to work for me.

ls | wc -l will also work fine

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.

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 (eg on Linux and OSX). But your may have yet another different version of find .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM