如何检查数组项是否包含bash中的6位数

时间:2017-11-09 17:14:25

标签: arrays bash

我正在尝试运行一个循环来检查一个数组项是否包含一个正好有六位数的数字,如果它没有打印它。

while read -a course; do
    size=$[#course[@]]
done < tmp2
for ((j=1; j<=size; j++)); do
     if (( ${course[j]} != [0-9][0-9][0-9][0-9][0-9][0-9] )); then
         echo ${course[j]}
     fi
done

while循环将一行从tmp2插入到数组中。

然后我想使用for来检查每个元素,如果它没有六位数字,则只使用printf。 tnx提前!

1 个答案:

答案 0 :(得分:5)

#!/usr/bin/env bash
#              ^^^^- not /bin/sh

re='^[[:digit:]]{6}$'                    # store our regex in a variable

while read -r -a courses; do             # for each line in the input file
  for course in "${courses[@]}"; do      # ...for each column in the line...
    if ! [[ $course =~ $re ]]; then      # ...if that column doesn't match our regex...
      printf '%s\n' "$course"            # ...then print its contents.
    fi
  done
done <tmp2