0

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

petr
  • 51
  • 1
  • 7

4 Answers4

1

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.

Community
  • 1
  • 1
fejese
  • 4,601
  • 4
  • 29
  • 36
1

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
Community
  • 1
  • 1
Austin Phillips
  • 15,228
  • 2
  • 51
  • 50
0

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
chepner
  • 497,756
  • 71
  • 530
  • 681
0

Another way. Assign $FOO to the positional parameters:

IFS=';'
set -- $FOO
echo  "$2"
Fritz G. Mehner
  • 16,550
  • 2
  • 34
  • 41