简体   繁体   中英

How to recursively loop through files and add data derived from a certain file name in bash without using the find command?

I am new to bash & awk and am trying to learn how to loop through a few directories and add data from files with a certain name.

Let's say we have the following directories:

/scoresA/.scores
/scoresB/.scores
/scoresB/score/.scores
/scoresC/scores.txt
/scoresD/

The file .scores has scores for each person in the following format:

Jacob 6
Joe 7
Kyle 9

I want to recurse through these directories, only files with the name .scores and add the score for a certain person.

Here is the bash code I wrote to recurse through the files.

function runCheck {
    FILE_NAME=".scores"
    CAND=$1
    START_DIR=$PWD
    
    shopt -s dotglob
    for file in "$START_DIR"/**/*
    do
        if [[ $file == *"${FILE_NAME}"* ]]
        then
            # awk script here
        fi
    done
}

When I run the function, runCheck, I want to add the score for a given person. So, when I run runCheck "Jacob" I want to check every .scores file that exists and add his score and print it out. I'm very new to bash and am just trying to learn more, but I was unable to successfully recurse through all the files and total it. If anyone has any ideas I'd really appreciate it. Thanks!

If you actually want to recurse, you have to actually do that.

my_find () {
    local dir=$1
    local pat=$2
    for file in "$dir"/*; do
        if [ -d "$file" ]; then
            my_find "$file" "$pat"
        elif [ "${file##*/}" = "$pat" ]; then
            echo "$file"
        fi
    done
}

Usage example:

my_find . .scores | xargs awk 1

to run awk 1 on all .scores files in the current directory . and its subdirectories.

For comparison, the same with find would look like

find . -type f -name .scores -exec awk 1 {} +

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM