My file is written like:
apples,oranges,berries,cherries
beer,wine,shots
chocolate,icecream,cake,muffins
cherries,guacamole,lychee
I need to output the second to last word in lines that contain the word cherries using awk:
I want it to print:
food: berries, guacamole
cherries appeared: 0/2 times
I currently have:
/cherries/
BEGIN {print "food:";}
{for (NR in a) {
FS=",";
printf($(NF-1));j++;
if((NF-1)=="cherries"){$i++;}
}
}
END {print "cherries appeared" i/j "times"}
What happens is it just prints every line that has cherries in it (the entire line) and $i$ comes out with a value of 0, so here it would print:
food: apples,oranges,berries,cherriescherries,guacamole,lychee
cherries appeared: nantimes
cherries
appeared 0 times? You have it twice in your file. Where do you define thea
array? Why are you usingNR
in that loop?