How do I split a string against a character in BASH?

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


Solution 1:

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.

Solution 2:

You can use IFS but this is simpler:

echo "82a8-bd7d-986d-9dc9-41f5-fc02-2c20-3175-097a-c1eb"- \
  | while read -d - i; do echo "$i"; done

Please take notice of added - after string to split — read will ignore the last token otherwise.

Solution 3:

Another way with pattern matching and array:

AUTH_CODE='82a8-bd7d-986d-9dc9-41f5-fc02-2c20-3175-097a-c1eb'
array=( ${AUTH_CODE//-/ } )
for j in ${array[@]} ; do echo $j ; done

Solution 4:

Just use parameters expansion:

AUTH_CODE='82a8-bd7d-986d-9dc9-41f5-fc02-2c20-3175-097a-c1eb'
echo "${AUTH_CODE//-/$'\n'}"

Output:

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