Manfredo Manfredo - 9 days ago 6
Linux Question

pattern matching within two bash arrays

I found quite a few posts on this but couldn't put together the pieces to solve my issue. So say I have two arrays:

array1=( adir bdir anicedir )
array2=( adir anice )


I would like to have a third array like so

array3=( adir anicedir )


More specifically if the first 5 characters of the i-th element in
array2
match the first 5 characters of any element in
array1
then substitute
array2[i]
with
array1[i]

Answer

There's nothing particularly short, because bash isn't a data-processing language. You need to use a loop.

array1=( adir bdir anicedir )
array2=( adir anice )
array3=()

for val2 in "${array2[@]}"; do
    for val1 in "${array1[@]}"; do
        if [[ ${val1:0:5} == "${val2:0:5}" ]]; then
            array3+=("$val1")
            break
        fi
    done
done

Quoting the right-hand side of == ensures that literal string comparison, not pattern matching, is performed.