0

I have a CSV file like this:

2019.04.15;3.75;
2019.04.29;-5.17;
2019.05.01;7.5;
2019.05.06;0.5;
2019.05.13;0.25;
2019.05.20;-8.5;

I want to get the sum of the plus and the minus values off the second column.

I solved this with the following pipe using awk and grep:

plus=$(awk -F';' '{print $2};' "$file" |
      grep --invert-match "-" |
      awk '{s+=$1}END{print s}'
)

minus=$(awk -F';' '{print $2};' "$file" |
      grep "-" |
      awk '{s+=$1}END{print s}'
)

I'm pretty sure awk can do it on his own, by using one command, the question is how would it look like?

1

plus:

awk -F';' '$2~/^[^\-]/{s+=$2} END{print s}'  data

minus:

awk -F';' '$2~/^[\-]/{s+=$2} END{print s}'  data
1
  • Awesome, Thanks!
    – nath
    May 23 '19 at 0:13
1
$ set -f; IFS=" " 
$ set $(perl -F\; -lane '$A[$F[1]<0] += $F[1]}{print "@A"' "$file") 
$ plus=$1 minus=$2
0
1

One more awk solution:

awk -F\; 'BEGIN {plus=0;minus=0} 
{if ($2>0) plus+=$2; else minus+=$2; } 
END {minus=-minus; print plus minus}' input_filename
3
  • I get:awk: cmd. line:2: {if ($2>0) plus+=$2 else minus+=$2} awk: cmd. line:2: ^ syntax error when using this as script.
    – nath
    May 23 '19 at 19:43
  • 1
    @nath, will correct it shortly May 23 '19 at 19:50
  • 1
    nice one, cheers <3
    – nath
    May 25 '19 at 0:19

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.