0

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]

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

OK, though it still gives me no output. Does echo ${array3[@]} give to you the correct output?
Now I get echo ${array3[@]} adir anice but it should be echo ${array3[@]} adir anicedir. Anyway it already helps, I will try to figure it out. Thanks
Ah, misread the desired output. Fixed, and in a much simpler manner. Just use substring expansion ${<var>:<star>t:<length>} to compare the 5-character prefix of each array element to each other.
Yeah I think that now it's spot on. Thanks

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.