-1

I have the following code

...
year_a=2018
year_b=2021

for (( i=year_b; i>=year_a; i-=1 )); do
  printf "$i: "; grep -Eic "A-15-" <<< "$results"
done
...

Output:

2021: 0   
2020: 11
2019: 0
2018: 21

I wish to make the following output:

2020: 11 
2018: 21

i.e., print a year if grep gave a return output which is not equal to zero, but I don't quite understand how to build such a construction. It is necessary to execute the first command if the second has found the outcome. Maybe somebody can give me a direction, thank you.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
KarlsD
  • 649
  • 1
  • 6
  • 12
  • What does your input data look like please? And, forgetting abouf `grep` and exit statuses, what are you trying to do in simple English? Thank you. – Mark Setchell Sep 09 '20 at 19:48
  • 1
    How do you get different results from the same search and from the same input? – karakfa Sep 09 '20 at 20:07

2 Answers2

2

If you capture the output into a shell variable (instead of letting it be printed directly to the terminal), you can then only conditionally print it:

if resultCount=$(grep -Eic "A-15-" <<< "$results"); then
  echo "$i: $resultCount"
fi

This works because grep returns a zero (successful) exit status if-and-only-if it finds at least one match; and storing the command substitution's result does not itself modify exit status.

See How do I set a variable to the output of a command in Bash?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

You can filter the results with a grep after the loop.

for (( i=year_b; i>=year_a; i-=1 )); do
  printf "$i: "; grep -Eic "A-15-" <<< "$results"
done | grep -v " 0$"
Walter A
  • 19,067
  • 2
  • 23
  • 43