LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Parsing String. (https://www.linuxquestions.org/questions/linux-newbie-8/parsing-string-731850/)

msgforsunil 06-10-2009 01:31 AM

Parsing String.
 
Hello All,

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.

Thanks
Sunil Kumar

joel2001k 06-10-2009 03:10 AM

What programming language do you want to use?

May be the sscanf function in C

nuwen52 06-10-2009 08:25 AM

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.

fpmurphy 06-10-2009 10:52 AM

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


chrism01 06-10-2009 08:23 PM

Perl; use 'split()' fn.

ghostdog74 06-10-2009 09:10 PM

some other solutions here

jamescondron 06-10-2009 09:20 PM

No rule against asking across different sites, is there?

ghostdog74 06-10-2009 09:52 PM

Quote:

Originally Posted by jamescondron (Post 3569918)
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.

msgforsunil 06-11-2009 01:47 PM

Thanks for your replies.


All times are GMT -5. The time now is 04:26 PM.