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.

4
  • I don't understand how your directory structure should look. What is wrong with mkdir? Commented Apr 30, 2014 at 8:05
  • This might get you going in the right direction: stackoverflow.com/questions/1494178/… Commented Apr 30, 2014 at 8:08
  • value=`echo "dictionary[\'$key\']\ \=\ [\'$data1\',\ \'$data2\']"`, then mkdir $value, i think this will help Commented Apr 30, 2014 at 8:10
  • 1
    The OP said "dictionary", not "directory". Commented Apr 30, 2014 at 8:18

4 Answers 4

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"
Sign up to request clarification or add additional context in comments.

1 Comment

I did that now how to access the dictionary elements? Should I say echo $dictionary['2'] to access C and D?
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

Comments

1
#!awk -f
BEGIN {
  FS = "|"
}
{
  printf "dictionary['%s'] = ['%s', '%s']\n", $1, $2, $3
}

Comments

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

Comments

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.