Linux script

can anyone help in this
i have a file like

2089,success
2089,failure
2087,failure
2089,success
2087,failure.

i want output like.

2089,success=2,failure=1
2087,success=1,failure=2

thanks

Not exact what you like, but mat help you on you way

awk '{arr[$1]++; next} END {for (i in arr) { print i,arr }}' file

gives

2089,failure 1
2087,failure 2
2089,success 2
1 Like

Try

$ cat file
2089,success
2089,failure
2087,failure
2089,success
2087,failure

$ awk -F, -v SU="success" -v FA="failure" '{X[$1]++;Y[$1,$2]++;next}END{for(i in X){print i",",SU,Y[i,SU]?Y[i,SU]:0,","FA,Y[i,FA]?Y[i,FA]:0}}' file
2087, success 0 ,failure 2
2089, success 2 ,failure 1
1 Like

Can you explain the ?Y[i,SU]:0 in Y[i,SU]?Y[i,SU]:0 ?

Edit: Found it.
Print a 0 instead of blank if no hits :slight_smile:

1 Like

@pamu= its not increasing the value of success and failure its jst giving output lik this
2089, success 0 ,failure 0

Works fine. Try this.

echo "2089,success
2089,failure
2087,failure
2089,success
2087,failure
3011,success
2089,failure
3011,success
2087,failure
3011,success" | awk -F, -v SU="success" -v FA="failure" '{X[$1]++;Y[$1,$2]++;next}END{for(i in X){print i",",SU,Y[i,SU]?Y[i,SU]:0,","FA,Y[i,FA]?Y[i,FA]:0}}'

Gives

2087, success 0 ,failure 3
3011, success 3 ,failure 0
2089, success 2 ,failure 2
1 Like

Alternatively:

awk -F, '{A[$1]; B[$2]; C[$1,$2]++} END{for(i in A){p=i; for(j in B)p=p FS j "=" C[i,j]+0; print p}}' file
2 Likes

thnx everyone :slight_smile: @Scrutinizer = can u explain me d codes please :slight_smile:

I will try to explain it, not sure I get all of it :slight_smile:
-F, sets the filed separator to , , normal (1 space)
{A[$1]; B[$2]; C[$1,$2]++} reads all data into three array
A contains all numbers
B contains success or failure
C contains both

Everything is printed out.

END{for(i in A){p=i; for(j in B)p=p FS j "=" C[i,j]+0; print p}}

for(i in A) Starts a loop, one for each number
for(j in B) then start a new loop within the first loop to select success or failure
+0 if no hits are found, it normally prints a blank, but by adding 0 , it show 0 when nothing found. Some more simple solution compare a conditional test done here: C[i,j]?C[i,j]:0

1. first run of loop i give i=2089 p=i=2089
    a. first run of loop j gives j=success p=p=2089 + FS="," + j=success + "=" +numbers of success+0
    b. second run of loop j gives j=faulure p=p=2089,success=2 +FS="," + j=failure + "=" +numbers of failure+0
       This gives p=2089,success=2,failure=1  then print p

2. second run of loop i give i=2087 p=i=2087
    a.  p=2087,success=0
    b.  p=2087,success=0,failure=2
        print p=2087,success=0,failure=2