[英]Is there a better way to retrieve the elements of a delimited pair in bash?
I have entries of the form: cat:rat
and I would like to assign them to separate variables in bash. 我有以下形式的条目: cat:rat
,我想将它们分配给bash中的单独变量。 I am currently able to do this via: 我目前可以通过以下方式执行此操作:
A=$(echo $PAIR | tr ':' '\n' | head -n1)
B=$(echo $PAIR | tr ':' '\n' | tail -n1)
after which $A
and $B
are, respectively, cat and rat. 之后, $A
和$B
分别是猫和老鼠。 echo, the two pipes and all feels a bit like overkill am I missing a much simpler way of doing this? 回声,两个管道,都感觉有点过大了,我错过了一种更简单的方法吗?
Yes using bash parameter substitution 是的,使用bash参数替换
PAIR='cat:rat'
A=${PAIR/:*/}
B=${PAIR/*:/}
echo $A
cat
echo $B
rat
Alternately, if you are willing to use an array in place of individual variables: 或者,如果您愿意使用数组代替单个变量:
IFS=: read -r -a ARR <<<"${PAIR}"
echo ${ARR[0]}
cat
echo ${ARR[1]}
rat
EDIT: Refer glenn jackman's answer for the most elegant read
-based solution 编辑:请参阅glenn jackman的答案以获取最优雅的基于read
的解决方案
animal="cat:rat"
A=echo ${animal} | cut -d ":" -f1
B=echo ${animal} | cut -d ":" -f2
might not be the best solution. 可能不是最佳解决方案。 Just giving you a possible solution 只是给您一个可能的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.