views:

63

answers:

4

Lets say I have a variable which has values :

#!/bin/sh
    MYVARIABLE="first,second,third"

    for vars in MYVARIABLE
    do 
    echo $vars
    done

this above doesn't work what I want but it looks fine, this should print first second third without , I wan't it to be printed without , any sugestions?

+2  A: 
MYVARIABLE="first,second,third"
IFS=","
set -- $MYVARIABLE
for i in ${@}; do echo $i; done

# you can also use an array in cases where you want to use the values later on
array=($@)
for i in ${!array[@]}; do echo ${array[i]}; done
ghostdog74
@ghostdog74 I want this to function as a loop, not so I must echo item one by one, the size varies. tnx
London
Is there any advantage of `set` over just looping, like ar suggests?
Boldewyn
the for loop at the end does that already. The individual `echoes` are there just to show how you can accessed the parameters after setting the variable using `set`.
ghostdog74
@Boldewyn, if you use `set`, each field will be assigned a positional parameter, like $1, $2,$3 etc. Its useful if you want to get an exact field.
ghostdog74
Yes, but if I just want to loop over that stuff, like the question suggests, the detour over an array simply complicates the script, doesn't it?
Boldewyn
use arrays to store the values if you want to use them later. If you just want to iterate the values and do nothing else, then use what ar suggests, or see my edit's first `for` loop.
ghostdog74
OK, that's a reasonable use case for this alternative. +1
Boldewyn
+2  A: 

try

MYVARIABLE="first,second,third"

for vars in $(echo $MYVARIABLE | tr "," "\n")
do 
  echo $vars
done

Or if you use IFS, don't forget to set IFS back to the original one when done

MYVARIABLE="first,second,third"

OIFS=$IFS
IFS=","
for vars in $MYVARIABLE
do 
    echo $vars
done
IFS=$OIFS
Arrix
@Arrix what does this mean replace , with new line character?
London
@London right, you can replace it with space as well: try "," " "
Arrix
+9  A: 

Use IFS (the input field separator), eg.

#!/bin/sh
MYVARIABLE="first,second,third"
IFS=","

for vars in $MYVARIABLE
do 
  echo $vars
done
ar
+2  A: 

Not sure what you want to do with the content of MYVARIABLE, or how do you fill it, but a very good option to deal with CSV data is to use awk.

If you have just this variable to be printed:

echo $MYVARIABLE | awk 'BEGIN { RS="," }{ print $0 }'

If you have a CSV file and need to perform calculation/transformation on the data then you should let the awk to fetch the file, using someting like:

awk 'BEGIN { FS="," ; OFS="\n" } { print $1,$2,$3 }' filename.csv
(this is just an ideia, not really related to your question)

jyzuz