0

In awk I have a file that every line contains a number in the range between 1..16 in field $5. For Example:

X;X;X;X;1;X;X
X;X;X;X;8;X;X
X;X;X;X;25;X;X
X;X;X;X;5;X;X

I want to check the number in field $5 and print a message related to the value. For example:

1;in range
8;in range
25;not in range 
5;in range

I have this code below but it is kind of unhandy;

awk -F";" 'OFS";" {if (($5=="1" || $5=="2" || $5=="3" || $5=="4" || $5=="5" || $5=="6" || $5=="7" || $5=="8" || $5=="9" || $5=="10" || $5=="11" || $5=="12" || $5=="13" || $5=="14" || $5=="15" || $5=="16") && $5!="") print $5 OFS "in range"}
{if (!($5=="1" || $5=="2" || $5=="3" || $5=="4" || $5=="5" || $5=="6" || $5=="7" || $5=="8" || $5=="9" || $5=="10" || $5=="11" || $5=="12" || $5=="13" || $5=="14" || $5=="15" || $5=="16") && $5!="") print $5 OFS "not in range"}'

since I created an array;

arr=(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)

I tried to implement methods shown in here https://stackoverflow.com/a/15394738/14320738 like this but not succeeded:

awk -F";" 'OFS";" {if ($5=="${arr[*]}" && $5!="") print $5 OFS "in range"}
    {if (($5!="${arr[*]}" && $5!="") print $5 OFS "not in range"}'

Both array and awk command are under same script. I do not know how to do it with awk. Newbie here,

Thank you.

Edit: If there is a way to do with array method in awk I would appreciate that.

Edit 2: After helpful comments I come up to the conclusion that bash array can't be passed into awk array.

  • 2
    if you insist on using an array you would need to start by passing the array into `awk` via the `-v` flag (see this Q&A - [Can I pass an array to awk using -v?](https://stackoverflow.com/q/33105808/7366100) - for a discussion on how this isn't as easy as it sounds); alternatively, if you'll be using the same (static) array all the time then you could define the array within `awk` (eg, in a `BEGIN {...}` block); but if you have just a few contiguous ranges then I'd probably tweak RavinderSingh13's answer to include the desired ranges – markp-fuso Sep 27 '20 at 15:41
  • 1
    @AhmetSaidAkbulut : You have defined your Array as a bash array. You can't pass an bash array to an awk array. You could write the bash array to a file and read the file then into a bash array; or, since `arr` contains only numbers, you can turn it into an environment variable with all those number separated by a space, and inside awk split the content of this variable into an awk array. – user1934428 Sep 28 '20 at 07:26

2 Answers2

4

IMHO you need not to create an array here, you could simply run a condition in awk and print statements accordingly.

awk -F';' '{if($5>=1 && $5<=16){print $5"; in range"} else{print $5";not in range"}}' Input_file
RavinderSingh13
  • 101,958
  • 9
  • 41
  • 77
3

Use greater than and less than ...

awk -F";" '{ if ($5 >= 1 && $5 <= 10) print $5, "In range"; else print $5, "Not in range" }' <file>
michjnich
  • 1,498
  • 1
  • 10
  • 23