Reputation: 51
My code
FOO="aaa;bbb;ccc"
echo ${FOO##*;} # Result: ccc
echo ${FOO%%;*} # Result: aaa
how to get "bbb" from var FOO?
echo ${FOO???*} # Result: bbb
thank you
Upvotes: 0
Views: 499
Reputation: 4628
There's no explicit operator for that. Furthermore you can not nest these operators (see Nested Shell Parameter Expansion)
So you should use some temporary variable for the job:
FOO="aaa;bbb;ccc"
tmp=${FOO%;*}
tmp=${tmp#*;}
echo $tmp
Or you should convert it to an array.
Edited for the archive, thanks for the comment.
Upvotes: 1
Reputation: 17188
Another way. Assign $FOO to the positional parameters:
IFS=';'
set -- $FOO
echo "$2"
Upvotes: 0
Reputation: 530960
This doesn't exactly generalize well, but extracting the middle of 3 ;
-delimited fields can be accomplished with:
$ shopt -s extglob
$ FOO=aaa;bbb;ccc
$ echo ${FOO//+(${FOO##*;}|${FOO%%;*}|;)}
bbb
Breaking it down into steps makes it easier to see how it works:
$ C=${FOO##*;} # ccc
$ A=${FOO%%;*} # aaa
$ echo ${FOO//+($A|$C|;)} # Removes every occurance of $A, $C, or ; from FOO
Upvotes: 0
Reputation: 15746
As per jejese's answer you can use the #
and %
word splitting constructs.
FOO="aaa;bbb;ccc"
split=${FOO%;*}
final=${split#*;}
echo $final
produces:
bbb
Or you can use the IFS
bash field separator variable set to a semicolon to split your input based on fields. This probably simpler to use and allows you to obtain the second field's value using a single line of code.
FOO="aaa;bbb;ccc"
IFS=";" read field1 field2 field3 <<< "$FOO"
echo $field1 $field2 $field3
produces:
aaa bbb ccc
Upvotes: 1