0

I have a file status.txt which is in the following format:

1|A|B
2|C|D

Now i have to read this file in shell script and create a dictionary like:

dictionary['1'] = ['A', 'B']
dictionary['2'] = ['C', 'D']

I am able read the content of file using this:

while read line
    do
        key=$line | cut --d="|" -f1
        data1=$line | cut --d="|" -f2
        data2=$line | cut --d="|" -f3
    done < "status.txt"

Can anybody help me in creating the dictionary as mentioned above.

Sonal Maheshwari
  • 217
  • 2
  • 3
  • 12

4 Answers4

2

According your idea with while loop, here is the fix:

#!/usr/bin/env bash

while IFS="|" read -r key data1 data2
do 
  echo "dictionary['${key}'] = ['${data1}', '${data2}']"
done <"status.txt"
BMW
  • 38,908
  • 11
  • 90
  • 109
1

Change your assignment lines to be like this:

key=$(echo $line | cut -d"|" -f1)

And then add the following line

printf "dictionary['%d'] = ['%s', '%s']\n" $key $data1 $data2
rojomoke
  • 3,425
  • 1
  • 18
  • 28
1
#!awk -f
BEGIN {
  FS = "|"
}
{
  printf "dictionary['%s'] = ['%s', '%s']\n", $1, $2, $3
}
Zombo
  • 1
  • 55
  • 342
  • 375
1

According to the previous answers i could figure out a solution

#!/usr/bin/env bash

while IFS="|" read -r key data1 data2
do 
  echo "{'${key}' : {'${data1}', '${data2}'}},"
done <"status.txt"

So it will give the result something like as follows

{'key1' : {'data1', 'data2'}, 'key2' : {'data1', 'data2'}}

Then you can use this result in any other language. Example: Python - Convert the above dictionary string to json by
1. json.dumps(result) to convert single quotes tto double quotes
2. json.loads(result) to convert string to json

ahmed sharief
  • 83
  • 1
  • 13