Search code examples
regexbashrecursionfindwc

Recursively go through directories and files in bash + use wc


I need to go recursively through directories. First argument must be directory in which I need to start from, second argument is regex which describes name of the file.

ex. ./myscript.sh directory "regex"

While script recursively goes through directories and files, it must use wc -l to count lines in the files which are described by regex.

How can I use find with -exec to do that? Or there is maybe some other way to do it? Please help.

Thanks


Solution

  • Yes, you can use find:

    $ find DIR -iname "regex" -type f -exec wc -l '{}' \; 
    

    Or, if you want to count the total number of lines, in all files:

    $ find DIR -iname "regex" -type f -exec wc -l '{}' \; | awk '{ SUM += $1 } END { print SUM }'
    

    Your script would then look like:

    #!/bin/bash
    
    # $1 - name of the directory - first argument
    # $2 - regex - second argument
    
    if [ $# -lt 2 ]; then
      echo Usage: ./myscript.sh DIR "REGEX"
      exit
    fi
    
    find "$1" -iname "$2" -type f -exec wc -l '{}' \;
    

    Edit: - if you need more fancy regular expressions, use -regextype posix-extended and -regex instead of -iname as noted by @sudo_O in his answer.