Search code examples
bashfind

bash: count the number of the found filles


my script putted into the alias looking for all the files with the extension of the parmtop or prmtop and then print all of them with its size.

alias find_prmtop='find . -mindepth 1 -maxdepth 100 \( -type f -name ".parmtop" -o -name "*.prmtop" -o -name "*.parm7" -o -name "*.parmtop" \) -printf "%p %k KB \n"'

which gives me:

./MD_cluster10_1_300K/protein.prmtop 47360 KB 
./MD_cluster11_1_300K/protein.prmtop 47104 KB 
./MD_cluster1_1_300K/protein.prmtop 43008 KB 
./MD_cluster2_1_300K/protein.prmtop 50176 KB 
./MD_cluster3_1_300K/protein.prmtop 50176 KB 
./MD_cluster4_1_300K/protein.prmtop 39808 KB 
./MD_cluster5_1_300K/protein.prmtop 47488 KB 
./MD_cluster6_1_300K/protein.prmtop 46976 KB 
./MD_cluster8_1_300K/protein.prmtop 51072 KB 
./MD_cluster9_1_300K/protein.prmtop 48128 KB 

how could I additionally count these filles and add at the end "The total number of the detected files is : number" ??


Solution

  • Aliasses are nice for relatively simple command substitution. If you want to do something more elaborate, you should use a function. Something like:

    find_prmtop(){
        local tmp=$(mktemp -t hoppa.XXXXXXXX)
        find . -mindepth 1 -maxdepth 100 \( -type f -name ".parmtop" -o -name "*.prmtop" -o -name "*.parm7" -o -name "*.parmtop" \) -printf "%p %k KB \n" |
            tee $tmp
        echo -n "The total number of the detected files is : "
        wc -l $tmp
        rm -f $tmp
    }
    

    --------edit---------

    This will work as long as there are no files *.prmtop, *.parm7 or *.parmtop with newlines in their name. Otherwise, the count may be wrong.

    find_prmtop(){
        local tmp=$(mktemp -t hoppa.XXXXXXXX)
        find . -mindepth 1 -maxdepth 100 \( -type f -name ".parmtop" -o -name "*.prmtop" -o -name "*.parm7" -o -name "*.parmtop" \) -printf "%p %k KB \n"
        find . -mindepth 1 -maxdepth 100 \( -type f -name ".parmtop" -o -name "*.prmtop" -o -name "*.parm7" -o -name "*.parmtop" \) -ls | wc -l       
    }
    

    will work if you have filenames with a newline in it, but if the tree is large, it will take more time.