Score:0

shell script: How to create a dictionary from the list?

cn flag
#!/usr/bin/env bash
b=$(awk -F "[|]" '{print $1}' test.txt)
days=$(awk -F "[{}]"  '{print $1}' test.txt) #days
time=$(awk -F "[{}]"  '{print $2}' test.txt) #time
#count=`echo $d | wc -l`
#echo $count
declare -A arr
for i in $days;do
        echo $i
    for j in $time;
        echo $j
    done
done

test.txt:

azureuser@disk-bkp:~$ cat test.txt
 Mo Tu We Th Fr {19:00 18:00 16:00 19:00 19:00}

The below one is the output from the above code :

Mo
19:00
18:00
16:00
19:00
19:00
Tu
19:00
18:00
16:00
19:00
19:00
We
19:00
18:00
16:00
19:00
19:00
Th
19:00
18:00
16:00
19:00
19:00
Fr
19:00
18:00
16:00
19:00
19:00

expected output is :

Mo
 19:00
Tu
18:00

We
16:00
Th
19:00

Fr
19:00

I wanted to create a key/value pairs based above lists and I need to get the value based on the key. $days output is Mo Tu We Th Fr and $time is 19:00 23:00 16:00 23:00 15:00. Expected Output is Mo:19:00 Tu:23:00 We:16:00 Th:23:00 Fr:15:00

bac0n avatar
cn flag
Edit your question with additional info on how *text.txt* is organized.
Score:0
cn flag

If you want to use awk for the setting of the key/value array you need to change your input file to:

Mo 19:00
Tu 18:00
We 16:00
Th 19:00
Fr 19:00

Then

awk '{a[$1]=$2} END {for (i in a) print i, a[i]}' test.txt 

Tu 18:00
We 16:00
Fr 19:00
Mo 19:00
Th 19:00

a[] is the key/value array you want. But as you can see the order has changed by awk. To prevent this we further change your input file to:

1Mo 19:00
2Tu 18:00
3We 16:00
4Th 19:00
5Fr 19:00

so we can restore the order using the first column later. Then

awk '{a[$1]=$2} END {for (i in a) print i, a[i]}' test.txt | sort -k1 | cut -c 2- | tr '\n' ' '

Which gives the output you want:

Mo 19:00 Tu 18:00 We 16:00 Th 19:00 Fr 19:00

But be aware that the keys in array a[] now contain the additional column which you may not want.

hariraj avatar
cn flag
Hi Mr Elm, actually I'm appending output of **tag=`curl -s -H Metadata:true --noproxy "*" "http://169.254.169.254/metadata/instance/compute/tagsList?api-version=2019-06-04"| jq -r '.[]|select(.name == "auto_stop").value' | cut -d '' -f1 | sed 's/[][]//g' ` to test.txt
hariraj avatar
cn flag
so from test.txt file contains **Mo Tu We Th Fr {19:00 18:00 16:00 19:00 19:00}**
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.