Issue
I'm trying to compare two arrays in a loop one array with file names and other array with file path including filename. I'm not able to use wild cards in my code. Please give your views and suggestions if I can work in any other way.
.~/.env
defaultlist = ("file1" "file2" "file3") #contains only filename
checklist=/filepath=("${filename}"/*.csv) # second array which is extracts all csv files in the path
for i in "${defaultlist[@]}". #iterating default list
do
if [["$i" =~ "$checklist[@]}"]]
then echo "$i File present"
else echo "$i not present"
fi
done
For better understanding, the above code will only match complete identical names in both lists but in my case one list has just filenames and the other list has filepath/filename appended with random numbers. So can we use the wild card while comparing two arrays? If not is there any other way to achieve my target?
Both arrays will not be of the same length.
Solution
For better understanding, the above code will only match complete identical names in both lists…
Not really, because the code above is malformed. 😉
One can always do something ugly and “quadratically” (meaning ${#defaultlist[@]} × ${#checklist[@]}
) complex to cross-match the lists:
defaultlist=('file1' 'file2' 'file3')
checklist=("${defaultlist[@]/%/".$((RANDOM)).suffix"}")
checklist=("${checklist[@]/#/'/some/path/to/'}")
defaultlist+=('file4' 'file5') # Not in checklist.
printf 'defaultlist: [%s]\nchecklist: [%s]\n\n' \
"${defaultlist[*]}" "${checklist[*]}"
for name_fragment in "${defaultlist[@]}"; do
for full_path in "${checklist[@]}"; do
if [[ "${full_path##*/}" == *"$name_fragment"* ]]; then
echo "${name_fragment} present"
continue 2
fi
done
echo "${name_fragment} NOT present"
done
Answered By - Andrej Podzimek