0

write the unix command to display roll, name and avg of all students whose score is more than 50 in each subject and average is more than or equal to 75.

avg can be calculated as (subj_1+subj_2)/2.

input:

roll ,name,subScore1,subScore2 123,a,88,78 101,b,76,90 812,c,78,98 

output:

123 a 83 812 c 78 

my code:

awk 'BEGIN {FS=',';OFS=' '} {if(NR>1 (&& $3>50 && $4>50) && ($3+$4)/2 >= 75){print $1,$2,($3+$4)/2}}' input_file 

I don't know why I'm getting error. please help guys.

8
  • NR>1 -e awk is not shell, it has it's own (different) language. There is no -e. What do you mean by -e? What should it do? Commented Jun 12, 2020 at 7:16
  • yes that typo you can use "&&" instead of -e Commented Jun 12, 2020 at 7:19
  • 1
    @AkshaySingh, you need not to set OFS as space since its default value itself will be space. Logic wise it looks ok but I haven't tested it, also you don't need && in few places which I believe you are already aware of. Thanks for sharing your efforts, keep it up and make sure you always add your efforts in form of code in your questions which is highly encouraged on SO, happy learning. Commented Jun 12, 2020 at 8:31
  • 1
    Thanks Sir, for your fast feedback as usual, keep us motivated... Commented Jun 12, 2020 at 12:20
  • 1
    You can't use single quotes in a single-quote-delimted string (including scripts) in any shell. Instead of awk 'BEGIN {FS=',';OFS=' '}, syntactically you need awk 'BEGIN {FS=",";OFS=" "} (but of course OFS=" " isn't actually doing anything as that's the default setting). wrt if(NR>1 (&& $3>50... - there's no language I'm aware of where you'd write cond1 (&& cond2) instead of cond1 && (cond2) just like you did in the rest of your script. Commented Jun 12, 2020 at 15:06

1 Answer 1

2

EDIT: Adding more generic solution where OP's Input_file could have more than 4 fields/columns in that case one could try following.

awk ' BEGIN{ FS="," } FNR==1{ next } { for(i=3;i<=NF;i++){ if($i>=50){ ++count } sum+=$i } avg=(sum/count) if(count==(NF-2) && avg>=75){ print $1,$2,avg } count=sum=avg=0 } ' Input_file 


Could you please try following, written and tested with shown samples with GNU awk.

awk ' BEGIN{ FS="," } FNR==1{ next } avg=($3+$4)/2 avg>=75 && ($3>=50 && $4>=50){ print $1,$2,avg } ' Input_file 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.