0

I have a student csv file containing fields with student data and the mailadress of the teacher in charge at the end. I try to automatically send only one email to the teacher containing all his students (using sendemail). The mail part is no problem but i cannot get the data out of the csv they way I want it. The csv file is created daily and contains a different number of students every day.

aer,kdx,mail1
dke,kad,mail2
err,qqq,mail1
qpi,bcc,mail1
bkd,onk,mail2
kcc,mnb,mail3

I tried to use awk and put all lines containing the same mailadress in an array but failed with that approach.

In this example it should send 3 mails. First containing

aer,kdx
err,qqq
qpi,bcc

Second containing

dke,kad
bkd,onk

Third containing

kcc,mnb

Thanks for any hints

0

You can use awk to create 3 files with the respective contents $1 and $2 with filename derived from $3:

With GNU awk:

awk 'BEGIN{OFS=FS=","}{print $1,$2 > $3"_out.csv"}' student.csv

Standard awk:

awk 'BEGIN{OFS=FS=","}{out=$2"_out.csv"; print $1,$2 >> out; close(out)}' student.csv

Then loop these files and send your email:

for m in *_out.csv; do
    _mail_command_
done
3
  • Thanks for the quick reply! The idea is very good. Unfortunately, I get: syntax error at source line 1 context is BEGIN{OFS=FS=","}{print $1,$2 > >>> $8"_out.csv" <<< awk: illegal statement at source line 1 I work on macOS – Jerome Arnold May 7 at 10:35
  • Awesome, thank you so much for your help! This works perfectly!! I would have never been able to figure that out myself. – Jerome Arnold May 7 at 12:13
  • 1
    Thanks, Ed! I added your version to my answer if that is ok :-) – pLumo May 7 at 12:25
1

I'd do this as:

sort -t, -k3,3 student.csv |
awk '
    BEGIN { FS=OFS="," }
    $3 != prev {
        close(out)
        out = $3 FS "out.csv"
        prev = $3
    }
    { print $1, $2 > out }
' ||
exit 1

for file in *,out.csv; do
    email="${file%,*}"
    send email to "$email" containing "$file"
done
0

command

for i in `awk -F "," '{if(!seen[$3]++)print $3}' filename`; do awk -F "," -v  i="$i" '$NF == i{print $1","$2}' filename >$i.csv; mailx -s "suject " -a "$i".csv $i</dev/null;done

Tested and worked fine

First we collecting unique email id and Fetching students who belongs to that email id and saving in file and sending email

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.