awk command to find the count of files ina directory

hi Gurus,

can anyone provide a awk command to get teh count of number of file sin a specific directory.

appreciate any kind of information..

thanks

This works but only if there actually are files in the directory... if there are only directories, or no files at all, it responds with an error and a '-1', because the 'ls -l' fails

ls -l *.* | wc | awk -F ' ' '{print $1-1}'
ls -1  |awk 'END{print NR}'

ls -l |grep '^-' | wc-l

OP had asked a solution with awk :slight_smile:

moreover the above could be modified as just

ls -1 | wc -l

By doing so, it wil count the directories also my dear pal

awk script for a specific directory (ie. a directory you specify) :

awk 'BEGIN {
	while ( ( "ls -l /yourdir" | getline line ) >0 ) {
		if ( line ~ /^-/ ){
			c++
		}
	}
	print "Total files: ", c
     }
'

or simply (for a specific directory):

ls -ltr | awk '/^-/{ c++;}END{print c}'

You are right, that would include directories as well.

My awk command should do then ! :slight_smile:

Thanks for pointing it out ! :slight_smile:

zsh:

with ...

set -- *(.D);num_files="${#@}"

.. and without dot files:

set -- *(.);num_files="${#@}"

matrixmadhan,

Use ls -l instead of ls -1 because it fails with filenames with spaces.

ls -1 | wc -l

also fails.

Regards

Am sorry that ls -1 won't fail for files having spaces in their names

if you are using ls -l instead of ls -1 then explicitly you need to subtract 1 from the result, if you are directly operating ls -l on wc -l.

I'm sorry you're right, I was confused to see that there was 1 less with ls -1 but I forgot the first line of ls -l.

Regards