My command looks like this:
cut -f 1 dummy_FILE | sort | uniq -c | awk ‘{print $2}’ | for i in $(cat -); do grep -w $i dummy_FILE |
awk -v VAR=”$i” ‘{distance+=$3-$2} END {print VAR, distance}’; done
cat dummy_FILE
Red 13 14
Red 39 46
Blue 45 23
Blue 34 27
Green 31 73
I want to:
For every word in $1 dummy_FILE (Red, Blue, Green) – Calculate sum of differences between $3 and $2.
To get the output like this:
Red 8
Blue -29
Green 42
My questions are:
-
Is it possible to replace
cut -f 1 dummy_FILE | sort | uniq -c | awk '{print $2}'?
I am usingsort | uniq -cto extract every word from the dataset – is it possible to do it with awk? -
How can I overcome useless
catinfor i in $(cat -)? -
grep -w $i dummy_FILEworks fine, but I want to replace it with awk (should I?); If so how can I do this?
When I am trying toawk -v VAR="$i" '/^VAR/ '{distance+=$3-$2} END {print VAR, distance}'I am getting"fatal: division by zero attempted".
Here’s one way using
awk:Results:
If you require sorted output, you could simply pipe into
sortlike arutaku suggests:You can however, print into
sort(within theawkstatement), like this: