Linux – How to split a string against a character in BASH

bashlinuxstringsUbuntu

I would like to be able to split an authorization code by the - character so that I can operate on each segment individually. I do not want to use external binaries (awk, grep) – this is to be as minimalistic as possible. What are some ways I can achieve this?

Here is an example auth code:

82a8-bd7d-986d-9dc9-41f5-fc02-2c20-3175-097a-c1eb

Best Answer

Try using the Internal Field Separator (IFS):

AUTH_CODE='82a8-bd7d-986d-9dc9-41f5-fc02-2c20-3175-097a-c1eb'

OIFS=$IFS                   # store old IFS in buffer
IFS='-'                     # set IFS to '-'

for i in ${AUTH_CODE[@]}    # traverse through elements
do
  echo $i
done

IFS=$OIFS                   # reset IFS to default (whitespace)

Output:

82a8
bd7d
986d
9dc9
41f5
fc02
2c20
3175
097a
c1eb

By setting the Internal Field Separator, you split AUTH_CODE on the - character, allowing you to traverse through the newly-created elements in a foreach loop.