I'm having some Trouble with Bash's associative Arrays: I'm looking for a Solution to assign an Array with Filenames to the associative Array.
It should look like :
/Applications/Setup.app => ([0] = "/Applications/Setup.app/[email protected]"
[1] = "/Applications/Setup.app/[email protected]"
[2] = "/Applications/Setup.app/IDMusic [email protected]")
Declaring the Dictionary / Hash Table / Associative Array isn't the Problem :
declare -A Dictionary
To get the Keys I'm using "readarray", combined with "find" :
readarray -d '' Applications < <(find "/Applications" -name "*.app" -print0)
If a Directory has a Whitespace in it's Name it's not a Problem. Now I need to find the PNG-Files in Application's Directory :
if [ ${#Applications[*]} -gt 0 ]; then
for App in "${Applications[@]}"; do
readarray -d '' Files < <(find "$App" -iname "*.png" -type f -print0)
for File in "${Files[@]}"; do
Dictionary["$App"]+="$File"
done
done
fi
The Problem which I didn't understand is, how can I add the Result of second "find" to the declared associative Array as List of Files ? If I set the readarray with Delimiter ' ' some Files, containing Whitespaces, were broken.
The next Question is how can I get the Values in a for-Loop ? I tried this also with readarray, but this didn't work for Files with Whitespaces in it's Name.
for Key in "${!Dictionary[@]}"; do
readarray -d ' ' Values <<< "${Dictionary[$Key]}"
for Value in "${Values[@]}"; do
echo "$Value"
done
done
If I run the above Script this is what I get :
/Applications/Setup.app/[email protected]/Applications/Setup.app/[email protected]/Applications/Setup.app/IDMusic
[email protected]
But I want this One :
/Applications/Setup.app/[email protected]
/Applications/Setup.app/[email protected]
/Applications/Setup.app/IDMusic [email protected]
Is there any Chance getting this Work with Bash 5.0.3 ?
The Goal is to use most of the Features without awk / grep / sed, so it runs with Bash's Built-In Commands.
jq. But really, if you need 2-dimensional arrays, you shouldn't be usingbashin the first place. Use a programming language with real data structures.