I have a csv file that looks like this:


and a directory that has a empty file named after the user

$ ls /dir/*

I want to look for the file and save its name into an array, then search that name through the csv record, add all of that name's 2nd and 3rd column, for all rows, and also shows if the user value exceed ex:400

Example results:

user1 has exceed 400
user2 has exceed 400

I'd really appreciate some help. Currently I'm trying with this, but no results:

shopt -s nullglob
cd /dir/

for ((i=0; i<${#ARRAY[@]}; i++)); do
    awk '
    BEGIN{FS=OFS=","} {$name += (($2+$3))} 
    END{for (j in a) printf "%s | %0.2f\n", j, a[j]}
    ' /dir.csv

Or maybe is there a simpler method where no need to save filename into an array?

1 Answer 1


I suggest

for f in dir/*; do awk -F ',' '$1==f{s+=$2+$3}END{print f","s;if(s>400)print f" has exceeded 400"}' f="$(basename "$f")" dir.csv; done

Or in unwinded, equivalent form:

for f in dir/*; do 
    awk -F ',' '
            print f","s
            if(s>400)print f" has exceeded 400"
    ' f="$(basename "$f")" dir.csv

For each file inside dir/, its basename (i.e., the name without the path) is passed to the awk script as the variable f.

In the awk script, the field separator is set to comma with -F ','. Then, if the first field of dir.csv is equal to f, the sum of 2nd and 3rd fields is added to s. If the sum exceeds 400, the message is included.

  • Wow, ok this is great.. But if i want to add a new function to check if the value exceed ex: 400 and print "value exceed", how would i add that, thank you.. Commented Aug 15, 2020 at 13:33
  • ok i have edited them, i think i already got them, but i still want to refer to your answer Commented Aug 15, 2020 at 13:40
  • nvm, this seems great. thank you for your help, i really appreciate them.. Commented Aug 15, 2020 at 13:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .