0

Looking for a smarter way to do something I'm doing already.

I have a string: "firstbit.secondbit.thirdbit.fourthbit.fifthbit.sixthbit"

The content between the periods changes, but the delimited position in the string is important.

This string will sometimes contain 3 parts only: "firstbit.secondbit.thirdbit"

I need to assign each part to a different variable. So, I'm currently using this uglyness:

#!/bin/sh
var="firstbit.secondbit.thirdbit.fourthbit.fifthbit.sixthbit"

first="$(echo $var | cut -d'.' -f1 )"
second="$(echo $var | cut -d'.' -f2 )"
third="$(echo $var | cut -d'.' -f3 )"
fourth="$(echo $var | cut -d'.' -f4 )"
fifth="$(echo $var | cut -d'.' -f5 )"
sixth="$(echo $var | cut -d'.' -f6 )"

What I'm hoping for is something more like:

echo "$var" | (magic command to assign values to variables here) first second third fourth fifth sixth

So that later on I can:

echo "[$first]"

[firstbit]

echo "[$third]"

[thirdbit]

and so on.

Arrays are no good as I prefer named variables for this system. Can't help but think that there's probably something in awk that can do this but I'm not intimately familiar with it.

Any thoughts?

teracow
  • 352

1 Answers1

3
IFS=. read -r first second third fourth fifth <<< "$var"

This sets the field separator to "." then tells bash to read into the named variables from the input provided by your $var's contents.

iruvar
  • 16,725
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255