从用管道分隔的键值对中获取值

从用管道分隔的键值对中获取值

我有一个字符串如下

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

相关内容