1

I have two arrays and I want to create them as a key/value pairs, i.e., build an associative array out of them.

This is my code:

#!/bin/bash

a=$(awk -F{ '{print $1}' test.txt) #output:  [Sun Mon Tues Wed Thu Fri Sat]
b=$(awk -F "[{}]" '{print $2}' test.txt)  #output:  [03:00 05:00 07:00 03:00 05:00 07:00 07:00]

declare -A arr
for j in $b
do
    time=$j
    for k in $a; do
        days=$k
        arr["$days"]=$time
    done
done

echo ${arr[@]} # o/p: 07:00 07:00 07:00 07:00 07:00 07:00 07:00

I'm getting this output:

"07:00 07:00 07:00 07:00 07:00 07:00 07:00"

but I'm expecting

03:00 05:00 07:00 03:00 05:00 07:00 07:00

How can I do that?

4
  • I've edited your question, please double check that the actual and expected output are correct (are there double quotes, square brackets?). Also, it would be helpful if you showed your input text file. Commented Oct 5, 2021 at 10:17
  • $b and $a are strings. Did you mean "${b[@]}" and "${a[@]}"? Commented Oct 5, 2021 at 10:24
  • It would help if you could paste a sample of your input file in a code block. Commented Oct 5, 2021 at 10:25
  • Why do for j in ... time=$j ... and not just for time in ...? Commented Oct 5, 2021 at 10:25

1 Answer 1

1

It is usually a bad idea to use awk multiple times on the same content, also bash shell has built-in support for reading delimited fields. Here is how you could process your file to populate the array:

#!/usr/bin/env bash

declare -A arr

# Iterate reading fields delimited by any of [{}] into k v variables
while IFS='[{}]' read -r k v; do
  arr["$k"]="$v" # Populate associative array
done <test.txt # from this file

# Print joined values from arr formatted inside brackets
printf '[%s]\n' "${arr[*]}"
Sign up to request clarification or add additional context in comments.

3 Comments

How can I get value based on key in arrays?
When I'm adding for loop getting entire key single row
When I'm adding for loop getting entire key as a single row Sun Mon Tues Wed Thu Fri Sat. How do I get one by one.?

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.