Bash to count folders in the current directory excluding others with a given name

0

In Linux I need to count the number of folders that are contained in the current folder, excluding a pair with these names: $ RECYCLE.BIN and System Volume Information.

In total there are 53 files without counting the two that I need to exclude, but I still can not make the filter.

What I am using now would be the following command:

ls -l | wc -l
    
asked by Jordan Blake Told 04.10.2018 в 17:24
source

2 answers

1

You can use grep with the parameter -v to exclude files or directories that you do not want to count:

ls | grep -v $RECYCLE.BIN | grep -v "System Volume Information" | wc -l
    
answered by 04.10.2018 в 20:45
1

In general, the answer by blonfu works. However, Linux has the curious virtue of allowing file names to contain line breaks:

$ touch "hola" "hola que
> tal"
$ ls | wc -l
       3     # incorrecto, hay 2 ficheros solamente

Therefore, it can be safer to do a find that runs through all the cases that interest us (that is, only at this level, without entering subdirectories) and print a character for each file it finds. Then, add characters:

find . -maxdepth 1 -mindepth 1 ! -print0 | xargs -0 -I {} sh -c 'echo .' | wc -l

Discarding the names you indicate:

find . -maxdepth 1 -mindepth 1 ! -name '$RECYCLE.BIN' ! -name 'System Volume Information' -print0 | xargs -0 -I {} sh -c 'echo .' | wc -l

In the previous case it returns:

$ find . -maxdepth 1 -mindepth 1 -print0 | xargs -0 -I {} sh -c 'echo .' | wc -l
       2

Or you can also do a loop that does the same:

$ for f in *; do echo "."; done | wc -l
       2

Discarding those names:

for f in *; do [ "$f" = '$RECYCLE.BIN' -o "$f" = 'System Volume Information' ] && continue; echo "."; done | wc -l
    
answered by 05.10.2018 в 10:08