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

3 Answers 3

4

You can use grep -f using process substitution:

grep -Ff <(printf "%s\n" "${LIST[@]}") <(printf "%s\n" "${server_client_list[@]}")
Sign up to request clarification or add additional context in comments.

3 Comments

Do I need to add a for loop, so that it loops though each string in LIST[@ array?
@doanerock Try it yourself... a=(1 2) ; printf "%d\n" "${a[@]}"
@doanerock: You don't need to loop. This command will find matching elements of LIST that are present in server_client_list array.
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.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.