2

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?

4 Answers 4

9

Use IFS (the input field separator), eg.

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

for vars in $MYVARIABLE
do 
  echo $vars
done
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

what does this mean replace , with new line character?
@London right, you can replace it with space as well: try "," " "
2
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

7 Comments

@ghostdog74 I want this to function as a loop, not so I must echo item one by one, the size varies. tnx
Is there any advantage of set over just looping, like ar suggests?
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.
@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.
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?
|
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.