Skip to main content
added 468 characters in body
Source Link
krb686
  • 559
  • 2
  • 4
  • 16

Granted you did ask for a solution with awk, but I think the sed solution is a bit more clear.

str="Joe:Johnson:25"
array=($(echo "$str" | sed 's/:/ /g'))
for el in "${array[@]}"; do
    echo "el = $el"
done

This gives:

el = Joe
el = Johnson
el = 25

In this case, you have to be sure not to put double quotes around the command expansion, so you don't end up with a single string element.

And this doesn't work for elements that contain spaces, of course. If you had:

str="Joe:Johnson:25:Red Blue"

You'd end up with

el = Joe
el = Johnson
el = Red
el = Blue

But if you don't mind using eval, you can insert quotes before the array assignment to get it to work.

eval "array=($(echo "\"$str\"" | sed 's/:/" "/g'))"

# Before the eval, it turns into:
eval "array=("Joe" "Johnson" "25" "Red Blue")"

Granted you did ask for a solution with awk, but I think the sed solution is a bit more clear.

str="Joe:Johnson:25"
array=($(echo "$str" | sed 's/:/ /g'))
for el in "${array[@]}"; do
    echo "el = $el"
done

This gives:

el = Joe
el = Johnson
el = 25

In this case, you have to be sure not to put double quotes around the command expansion, so you don't end up with a single string element.

Granted you did ask for a solution with awk, but I think the sed solution is a bit more clear.

str="Joe:Johnson:25"
array=($(echo "$str" | sed 's/:/ /g'))
for el in "${array[@]}"; do
    echo "el = $el"
done

This gives:

el = Joe
el = Johnson
el = 25

In this case, you have to be sure not to put double quotes around the command expansion, so you don't end up with a single string element.

And this doesn't work for elements that contain spaces, of course. If you had:

str="Joe:Johnson:25:Red Blue"

You'd end up with

el = Joe
el = Johnson
el = Red
el = Blue

But if you don't mind using eval, you can insert quotes before the array assignment to get it to work.

eval "array=($(echo "\"$str\"" | sed 's/:/" "/g'))"

# Before the eval, it turns into:
eval "array=("Joe" "Johnson" "25" "Red Blue")"
Source Link
krb686
  • 559
  • 2
  • 4
  • 16

Granted you did ask for a solution with awk, but I think the sed solution is a bit more clear.

str="Joe:Johnson:25"
array=($(echo "$str" | sed 's/:/ /g'))
for el in "${array[@]}"; do
    echo "el = $el"
done

This gives:

el = Joe
el = Johnson
el = 25

In this case, you have to be sure not to put double quotes around the command expansion, so you don't end up with a single string element.