Linux - NewbieThis forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
I have a case, wherein I have a string of the format
"attr1=value1 attr2=value2 attr3=value3 attr4=value4"
How do I extract the value associated with for a given attributename. For eg. I need to get a value of "value2" when I give an input for attribute name as "attr2". Note, each attribute values is space seperated and value can contain / or , or - as part of it.
Distribution: CentOS 5, Gentoo, FreeBSD, Fedora, Mint
Posts: 136
Thanked: 22
The language choice is useful here.
But, I'll add my two cents anyway. In python, you can split the string (based on " ") and feed that into a list comprehension (splitting the resulting strings based on "=") with an output to the dict function. This can be done in 1 line and gives a dictionary with values indexed by attributes.
This works with any number of key=value pairs in the string.
One way is to use an associative array if your shell supports the concept.
Code:
#!/usr/bin/ksh93
typeset -A aArray
str="attr1=value1 attr2=value2 attr3=value3 attr4=value4"
# split the string and store in temporary array
IFS="= " typeset -a tArray=($str)
# populate associative array
for ((i = 0; i < ${#tArray[@]}; i++))
do
aArray[${tArray[i]}]=${tArray[++i]}
done
# print contents of associative array
for i in "${!aArray[@]}"
do
print "aArray[$i] is ${aArray[$i]}"
done
The output from running this script is:
Code:
aArray[attr1] is value1
aArray[attr2] is value2
aArray[attr3] is value3
aArray[attr4] is value4
No rule against asking across different sites, is there?
I am merely posting to inform (not just to OP) of other solutions as some of the people in other forums might not be a member here. So some good solutions might be missed out.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.