简体   繁体   English

AWK:检查值是否存在于 bash 数组中

[英]AWK: check value if exists in bash array

In awk I have a file that every line contains a number in the range between 1..16 in field $5 .awk我有一个文件,其中每一行都包含字段$5 1..16范围内的数字。 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.我想检查字段$5的数字并打印与该值相关的消息。 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:我试图实现这里显示的方法https://stackoverflow.com/a/15394738/14320738像这样但没有成功:

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. array 和 awk 命令都在同一个脚本下。 I do not know how to do it with awk .我不知道如何用awk做到这一点。 Newbie here,新手来了,

Thank you.谢谢你。

Edit: If there is a way to do with array method in awk I would appreciate that.编辑:如果有办法在 awk 中处理数组方法,我将不胜感激。

Edit 2: After helpful comments I come up to the conclusion that bash array can't be passed into awk array .编辑 2:经过有用的评论后,我得出结论bash array 不能传递到 awk array

恕我直言,您不需要在此处创建数组,您可以简单地在awk运行一个条件并相应地打印语句。

awk -F';' '{if($5>=1 && $5<=16){print $5"; in range"} else{print $5";not in range"}}' Input_file

使用大于和小于...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM