AWK: controlla il valore se esiste nell'array bash

Sep 28 2020

In awkho un file che ogni riga contiene un numero nell'intervallo tra 1..16nel campo $5. Per esempio:

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

Voglio controllare il numero nel campo $5e stampare un messaggio relativo al valore. Per esempio:

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

Ho questo codice qui sotto ma è un po 'scomodo;

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.

Risposte

4 RavinderSingh13 Sep 27 2020 at 22:10

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
3 michjnich Sep 27 2020 at 22:11

Use greater than and less than ...

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