问题
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.
回答1:
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"
回答2:
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
回答3:
#!awk -f
BEGIN {
FS = "|"
}
{
printf "dictionary['%s'] = ['%s', '%s']\n", $1, $2, $3
}
回答4:
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
来源:https://stackoverflow.com/questions/23382726/how-to-create-dictionary-using-shell-script