issue Find command Linux

2.5k views Asked by At

I have a folder and I want count all regular files in it, and for this I use this bash command:

find pathfolder -type f  2> err.txt | wc -l

In the folder there are 3 empty text files and a subfolder with inside it other text files. For this reason I should get 3 as a result, but I get 6 and I don't understand why. Maybe there is some options that I did not set.

If I remove the subfolder I get 4 as result

2

There are 2 answers

12
Eugeniu Rosca On

Below solutions ignore the filenames starting with dot.

To count the files in pathfolder only:

find pathfolder -maxdepth 1 -type f -not -path '*/\.*' | wc -l

To count the files in ALL child directories of pathfolder:

find pathfolder -mindepth 2 -maxdepth 2 -type f -not -path '*/\.*' | wc -l

UPDATE: Converting comments into an answer

Based on the suggestions received from anubhava, by creating a dummy file using the command touch $'foo\nbar', the wc -l counts this filename twice, like in below example:

$> touch $'foo\nbar'
$> find . -type f
./foo?bar
$> find . -type f | wc -l
2

To avoid this, get rid of the newlines before calling wc (anubhava's solution):

$> find . -type f -exec printf '%.0sbla\n' {} +
bla
$> find . -type f -exec printf '%.0sbla\n' {} + | wc -l
1

or avoid calling wc at all:

$> find . -type f -exec sh -c 'i=0; for f; do ((i++)); done; echo $i' sh {} +
1
6
anubhava On

To grab all the files and directories in current directory without dot files:

shopt -u dotglob
all=(*)

To grab only directories:

dirs=(*/)

To count only non-dot files in current directory:

echo $(( ${#all[@]} - ${#dirs[@]} ))

To do this with find use:

find . -type f -maxdepth 1 ! -name '.*' -exec printf '%.0s.\n' {} + | wc -l