Dagang Wei
Dagang Wei

Reputation: 26498

extract multiple fields from a string

I have a string

"name1:value1, ... name2:value2, ... name3:value3, ...",

i want to extract value1, value2, value3 to var1, var2, var3. Is there simple solution in bash or python? The simpler the better.

Upvotes: 0

Views: 1484

Answers (5)

Hai Vu
Hai Vu

Reputation: 40733

Here is my bash solution. I take a great deal of time to make sure it is the simplest:

string="name1:value1,name2:value2,name3:value3"
varCount=0
for nameValuePair in $( tr , ' ' <<< $string )
do  
    IFS=:
    ((varCount++))
    set $nameValuePair
    eval var$varCount="$2"
done

# Do what you want with $var1, $var2, ... For example:
echo var3=$var3

Upvotes: 0

kurumi
kurumi

Reputation: 25609

$ echo "name1:value1, name2:value2, name3:value3" | awk -F",[ \t]*" '{for(i=1;i<=NF;i++){split($i,a,":");print a[2] } }'
value1
value2
value3

$ echo "name1:value1, name2:value2, name3:value3" | ruby -e 'print gets.split(",").each{|x| puts x.split(":")[-1]}'
value1
value2
value3

To capture to shell variable,

$ var=$(echo "name1:value1, name2:value2, name3:value3" | awk -F",[ \t]*" '{for(i=1;i<=NF;i++){split($i,a,":");print a[2] } }')
$ echo $var
value1 value2 value3
$ set -- $var
$ echo $1
value1
$ echo $2
value2

@Todd, please look at bash reference.

set [--abefhkmnptuvxBCEHPT] [-o option] [arg ...] .....
... Any arguments remaining after option processing are treated as values for the positional parameters and are assigned, in order,  to
          $1, $2, ...  $n..

--      If no arguments follow this option, then the positional parameters are unset.  Otherwise, the positional parameters are
                      set to the args, even if some of them begin with a -.

Upvotes: 2

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17198

Pure Bash:

declare string="name1:value1, name2:value2, name3:value3, name4:value4"

IFSsave=$IFS
IFS=','
declare -a array=( $string )                # split string into array
IFS=$IFSsave

for item in ${array[@]}; do
  item=${item/:/=}                          # substitute ':' to '='
  eval "${item/#name/var}"                  # substitute 'name' to 'var'
done

echo -e "the new variables : ${!var*}"

for v in ${!var*}; do
  echo -e "$v = ${!v}"                      # use indirect parameter expansion
done

Output:

the new variables : var1 var2 var3 var4
var1 = value1
var2 = value2
var3 = value3
var4 = value4

Upvotes: 3

user225312
user225312

Reputation: 131697

>>> s = "name1:value1,name2:value2, name3:value3"
>>> d = dict(e.split(':') for e in s.split(','))
>>> for count, values in zip(range(1, len(d)+1), sorted(d.itervalues())):
...     globals()['var{0}'.format(count)] = values
... 
>>> var1
'value1'
>>> var2
'value2'
>>> var3
'value3'

Pretty hack-ish, I know but then if there is a cleaner way, feel free to suggest :-) (Note: This is a generic solution and in case you need the keys of the dictionary, you can use that also with a slight change)

EDIT: Based on Thomas' comment:

>>> s = "name1:value1,name2:value2, name3:value3"
>>> d = dict(e.split(':') for e in s.split(','))
>>> d
{'name2': 'value2', ' name3': 'value3', 'name1': 'value1'}
>>> d['name2']
value2

Upvotes: 3

microo8
microo8

Reputation: 3784

when you have a string like "name1:value1, ... name2:value2, ... name3:value3, ..." then you can do this to dict: d = eval('{'+"name1:value1, ... name2:value2, ... name3:value3, ..."+'}') and then:

>>> print d['name1']
value1
...

Upvotes: 1

Related Questions