从字符串中提取多个字段

时间:2011-04-09 09:49:17

标签: python bash sed awk

我有一个字符串

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

我想将value1,value2,value3提取到var1,var2,var3。在bash或python中有简单的解决方案吗?越简越好。

5 个答案:

答案 0 :(得分:3)

>>> 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'

非常黑客,我知道但是如果有更清洁的方式,请随时提出:-)(注意:这是一个通用的解决方案,如果你需要字典的键,你也可以使用它略有变化)

编辑:根据托马斯的评论:

>>> 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

答案 1 :(得分:3)

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

输出:

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

答案 2 :(得分:2)

$ 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

要捕获到shell变量,

$ 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,请看bash参考。

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 -.

答案 3 :(得分:1)

当你有一个像"name1:value1, ... name2:value2, ... name3:value3, ..."这样的字符串时 然后你可以这样做dict: d = eval('{'+"name1:value1, ... name2:value2, ... name3:value3, ..."+'}') 然后:

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

答案 4 :(得分:0)

这是我的bash解决方案。我花了很多时间来确保它是最简单的:

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