Palace Chan
Palace Chan

Reputation: 9183

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. 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. echo, the two pipes and all feels a bit like overkill am I missing a much simpler way of doing this?

Upvotes: 1

Views: 61

Answers (3)

GeneticSmart
GeneticSmart

Reputation: 93

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

Upvotes: 0

iruvar
iruvar

Reputation: 23364

Yes using bash parameter substitution

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

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246764

Using the read command

entry=cat:rat
IFS=: read A B <<< "$entry"
echo $A    # => cat
echo $B    # => rat

Upvotes: 6

Related Questions