foo()
{
mapfile -t arr <<< "${1}"
for i in "${!arr[@]}"
do
if [ -z "${arr[$i]}" ]
then
unset arr[$i]
fi
done
}
When I pass a variable with some content in it ( a big string basically ), I would like to :
- interpret the first word before the first whitespace as a key and everything after the first whitespace becomes the entry for that key in my associative array
- skip empty lines or lines with just a newline
example ( empty lines not included for compactness )
google https://www.google.com
yahoo https://www.yahoo.com
microsoft https://www.microsoft.com
the array should look like
[ google ] == https://www.google.com
[ yahoo ] == https://www.yahoo.com
[ microsoft ] == https://www.microsoft.com
I haven't found any good solution in the bash manual for the 2 points, the function foo that you see it's kind of an hack that creates an array and only after that it goes through the entire array and deletes the entries where the string is null .
So point 2 gets a solution, probably an inefficient one, but it works, but point 1 still doesn't have a good solution, and the alternative solution is to just create an array while iterating with read, as far as I know .
Do you know how to improve this ?
read,readusually shuffles the entries around and it doesn't replicate the original order,mapfileusually keeps things in the same order as the original string/file .mapfilekeeps everything in the original order because it doesn't create an associative array.readhas nothing to do with the array you build, but presumably you are actually adding items one at a time to an associative array when you use it.mapfilethat creates associative arrays as described in my post, I don't have a final word about if this 2 points are doable or not with just the builtin commands from the bash .