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
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
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.
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
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
Another way. Assign $FOO to the positional parameters:
IFS=';'
set -- $FOO
echo "$2"