简体   繁体   English

Bash - 如何检查变量值是否在数组中

[英]Bash -how to check if variable value is in an array

I have an array that has 6 values, i then have three more arrays with anywhere between 4 and 1 value.我有一个有 6 个值的数组,然后我有另外三个 arrays 值在 4 到 1 之间。 i want to loop through array 1 and check if the value from array one appears in array2, array 3 and array 4. Currently i have the below but it only appears to check my value from array1 against the first value in arrays 2,3 and 4. i have omitted array 3 and 4 but they would have the same for loop as array2 and be inside the loop for array1.我想遍历数组 1 并检查数组 1 中的值是否出现在数组 2、数组 3 和数组 4 中。目前我有以下内容,但它似乎只检查我的数组 1 中的值与 arrays 2,3 中的第一个值和4. 我省略了数组 3 和 4,但它们将具有与数组 2 相同的 for 循环,并且位于数组 1 的循环内。

array1=("value1" "value2" "value3" "value4" "value5" "value6")

for i in "${array1}"; do

array2= ("value1" "value3" "value4" "value5")

for f in "${array2}; do
if [[ ${i} == ${f} ]]; then

echo "${i} in array1 matches ${f} in array2"
else
echo "${i} in array1 does not match any value in array2"
fi
done
done

I think that the best thing to do is to make a function我认为最好的办法是制作一个 function

in_array () {
  search=$1
  shift        # remove first argument from list of args $@
  for val; do  # equivalent to `for val in "$@"`
    if [[ $search = $val ]]; then
      return   # returns exit code of the successful [[ test ]], 0
    fi
  done
  return 1
}

This returns 0 if the value is found, else 1 , allowing you to use it like:如果找到该值,则返回0 ,否则返回1 ,允许您像这样使用它:

array1=("value1" "value2" "value3" "value4" "value5" "value6")
array2=("value1" "value3" "value4" "value5")

for i in "${array1[@]}"; do
  if in_array "$i" "${array2[@]}"; then
    echo "$i in array1 is in array2"
  fi
done

Note that to loop through all the values of an array, the correct expansion is "${array[@]}" (with double quotes and [@] ).请注意,要遍历数组的所有值,正确的扩展是"${array[@]}" (带有双引号和[@] )。

This is possible in a single loop:这在一个循环中是可能的:

#!/usr/bin/env bash

array1=("value1" "value2" "value3" "value4" "value5" "value6")
array2=("value1" "value3" "value4" "value5")

while read -r -d '' -n 8 count && IFS= read -r value; do
  if [ "$count" -gt 1 ]; then
    # value is seen more than once, so it is in both arrays
    echo "${value} in array1 matches ${value} in array2"
  else
    # value is only seen once
    if printf $'%s\n' "${array1[@]}" | grep --quiet "$value"; then
      # value is from array1
      echo "${value} in array1 does not match any value in array2"
    fi
  fi
done< <(
  # Combine both arrays
  # Sort and count number of times each value appears
  # then feed the while loop
  printf $'%s\n' "${array1[@]}" "${array2[@]}" | sort | uniq --count
)

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

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