0

Is it possible to grep an array in bash? Basically I have two arrays, one array I want to loop through and the other array I want to check to see if each string is in the other array or not.

Rough example:

for CLIENTS in ${LIST[@]}; do
    #lost as to best way to grep a array with out putting the values    in a file.
    grep ${server_client_list[@]}
done
anubhava
  • 761,203
  • 64
  • 569
  • 643
doanerock
  • 31
  • 2
  • 4

3 Answers3

4

You can use grep -f using process substitution:

grep -Ff <(printf "%s\n" "${LIST[@]}") <(printf "%s\n" "${server_client_list[@]}")
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You could use the following function :

function IsInList {
    local i
    for i in "${@:2}"; do
        [ "$i" = "$1" ] && return 0
    done
    return 1
}

for CLIENT in "${LIST[@]}"; do
    IsInList "$CLIENT" "${server_client_list[@]}" && echo "It's in the list!"
done

Note that the quotes around ${LIST[@]} and ${server_client_list[@]} are very important because they guarantee the array expansion to expand the way you want them to, instead of having a bad surprise when a space make its way into one of those array values.

Credits : I took this function from patrik's answer in this post when I needed something like that.

Edit :

If you were looking for something with regexp capabilities, you could also use the following :

function IsInList {
    local i
    for i in "${@:2}"; do
        expr match "$i" "$1" && return 0
    done
    return 1
}
Community
  • 1
  • 1
user43791
  • 284
  • 2
  • 10
0

Bash provides substring matching. This eliminates the need to spawn external processes and subshells. Simply use:

for CLIENTS in ${LIST[@]}; do
    if [[ "${server_client_list[@]}" =~ "$CLIENTS" ]]; then
        echo "CLIENTS ($CLIENTS) is in server_client_list"
    fi
done

Note: this works for bash, not sh.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85