![从用管道分隔的键值对中获取值](https://linux22.com/image/207421/%E4%BB%8E%E7%94%A8%E7%AE%A1%E9%81%93%E5%88%86%E9%9A%94%E7%9A%84%E9%94%AE%E5%80%BC%E5%AF%B9%E4%B8%AD%E8%8E%B7%E5%8F%96%E5%80%BC.png)
我有一个字符串如下
Delete :xna.del|mode:Full|Execution: loaded
我需要将输出存储在 3 个参数中。举个例子
a=xna.del
b=Full
c=loaded
答案1
使用zsh
代替bash
,将结果存储在关联数组中:
$ string='Delete :xna.del|mode:Full|Execution: loaded'
$ IFS=':|'
$ set -o extendedglob
$ typeset -A field=( ${=string//[[:space:]]#:[[:space:]]#/:} )
$ typeset -p field
typeset -A field=( [Delete]=xna.del [Execution]=loaded [mode]=Full )
$ print -r -- $field[mode]
Full
答案2
所以我猜“:”前面的词与你无关?
使用所有值的数组尝试此解决方案
#!/usr/bin/env bash
TEXT="Delete :xna.del|mode:Full|Execution: loaded"
MYVAR=( $(tr '|' '\n' <<< "${TEXT}" |cut -d: -f2) )
#Checks on the result
echo MYVAR has "${#MYVAR[@]}" entries
#single-Access
echo "${MYVAR[0]}"
echo "${MYVAR[1]}"
echo "${MYVAR[2]}"
#formated output
printf "\t%s\n" "${MYVAR[@]}"
#iterate again to work with it?
for value in "${MYVAR[@]}"; do echo "$value"; done