linux 中 awk 语句判断元素是否存在或者不存在于数组中

 

001、判断元素存在于数组中

(base) [b20223040323@admin1 test]$ ls
a.txt
(base) [b20223040323@admin1 test]$ cat a.txt           ## 测试数据
a 88
a 76
b 88
a 876
b 25
a 66                                                   ## 判断元素存在于数组中
(base) [b20223040323@admin1 test]$ awk 'BEGIN{ay["b"]=0} {if($1 in ay) {print NR, $0}}' a.txt
3 b 88
5 b 25

 

002、判断元素不存在于数组中

(base) [b20223040323@admin1 test]$ ls
a.txt
(base) [b20223040323@admin1 test]$ cat a.txt        ## 测试数据
a 88
a 76
b 88
a 876
b 25
a 66                                   ## 判断元素不在数组中
(base) [b20223040323@admin1 test]$ awk '{if(!($1 in ay)) {ay[$1] = $2}} END {for (i in ay) {print i, ay[i]}}' a.txt
a 88
b 88

 

 

posted @ 2024-01-31 16:34  小鲨鱼2018  阅读(165)  评论(0编辑  收藏  举报