6

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

5 Answers5

14

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.

Daniel Li
  • 985
5

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.

Tometzky
  • 2,709
4

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
adaptr
  • 16,746
ott--
  • 1,091
2

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
Thor
  • 475
0
for i in {1..10}; do echo '82a8-bd7d-986d-9dc9-41f5-fc02-2c20-3175-097a-c1eb'|cut -d"-" -f$i;done
Tom
  • 146