Shell数组中模糊检测

检测数组a中的元素是否模糊包含数组b中的一个或多个元素

 1#!/bin/bash
 2
 3# 数组a和数组b的定义
 4a=("tainan" "taipei" "taichung" "keelung" "taoyuan" "changhua" "nantou" "kinmen")
 5b=("tai" "nan")
 6
 7
 8for element_a in "${a[@]}"; do
 9    contains=false
10    for pattern in "${b[@]}"; do
11        if [[ $element_a =~ $pattern ]]; then
12            contains=true
13            break
14        fi
15    done
16    if [  "$contains" = true ] ; then
17      echo "----------$element_a符合要求---------------"
18    else
19      echo "**********$element_a不符合要求************"
20    fi
21done

下述改进版的,可避免双重循环

 1#!/bin/bash
 2
 3# 数组a和数组b的定义
 4a=("tainan" "taipei" "taichung" "keelung" "taoyuan" "changhua" "nantou" "kinmen")
 5b=("tai" "nan")
 6
 7# 将数组b中的元素连接成正则表达式
 8regex=$(IFS='|'; echo "${b[*]}")
 9
10for element_a in "${a[@]}"; do
11    if echo "$element_a" | egrep -iq "$regex"; then
12        echo "----------$element_a符合要求---------------"
13    else
14        echo "**********$element_a不符合要求************"
15    fi
16done