London
London

Reputation: 15274

for loop with bash from variable

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?

Upvotes: 2

Views: 280

Answers (4)

jyz
jyz

Reputation: 6199

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)

Upvotes: 2

ghostdog74
ghostdog74

Reputation: 342373

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

Upvotes: 2

Arrix
Arrix

Reputation: 2731

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

Upvotes: 2

a'r
a'r

Reputation: 36999

Use IFS (the input field separator), eg.

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

for vars in $MYVARIABLE
do 
  echo $vars
done

Upvotes: 9

Related Questions