LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   SUSE / openSUSE (https://www.linuxquestions.org/questions/suse-opensuse-60/)
-   -   parse comma delimited text string (https://www.linuxquestions.org/questions/suse-opensuse-60/parse-comma-delimited-text-string-733044/)

sunilvadranapu 06-15-2009 09:04 AM

parse comma delimited text string
 
in shell script, I need to know how to get from one comma delimited
text string to many strings.

from this:

main_string = "onE,Two,Three , fouR,five, six "

to these:

string1 = "one"
string2 = "two"
string3 = "three"
string4 = "four"
string5 = "five"
string6 = "six"


how to implement this in shell scipt? can anyone help?

weibullguy 06-15-2009 09:40 AM

Not pretty, hopefully it'll help you started.
Code:

#~/bin/sh

string="onE,Two,Three , fouR,five, six "

string1=$(echo $string | cut -f1 -d ',')
string2=$(echo $string | cut -f2 -d ',')
string3=$(echo $string | cut -f3 -d ',')
string4=$(echo $string | cut -f4 -d ',')
string5=$(echo $string | cut -f5 -d ',')
string6=$(echo $string | cut -f6 -d ',')

exit 0


forrestt 06-15-2009 09:55 AM

You really probably want to use arrays instead of strings.

Code:

#/bin/sh

main_string='onE,Two,Three , fouR,five, six'

COUNTER1=1

for NUMBER in `echo ${main_string} | sed -e 's/[, ]\+/\n/g' -e 's/\(.*\)/\L\1/'` ; do
        string[$COUNTER]=${NUMBER}
        let COUNTER1=COUNTER1+1
done

COUNTER2=1

while [ ${COUNTER2} -lt ${COUNTER1} ] ; do
        echo "string[${COUNTER2}] = ${string[${COUNTER2}]}"
        let COUNTER2=COUNTER2+1
done

HTH

Forrest

ghostdog74 06-15-2009 10:06 AM

there is no need to use so many cuts as in one of the example solution, and depending on what you want to do, sometimes, there's no need to use arrays. anyway, in bash
Code:

main_string="onE,Two,Three , fouR,five, six "
IFS=","
set -- $main_string
echo $1
echo $2 # and so on

personally, i prefer awk
Code:

echo $main_string | awk -F"," '{print $1, $2 ...}'

sunilvadranapu 06-16-2009 12:05 AM

Hi forrestt,
thanks for your quick reply. your code suited exactly for my requirement. thanks you very much.


-SUN


All times are GMT -5. The time now is 03:53 AM.