String Manipulation Question....

Say I've got a string like: data1,data2,data3,data4.

How would I be able to break up the string, so that I have four variables w/ the values data1 data2 data3 data4.

Also, how could I read a string character by character.

I know you can read a sentence word by word by using the
for var in $othervar, but how would you read a string character by character.

Thanks in Advance,
AJ Allmendinger

Say I've got a string like: data1,data2,data3,data4.

How would I be able to break up the string, so that I have four variables w/ the values data1 data2 data3 data4.

Also, how could I read a string character by character.

I know you can read a sentence word by word by using the
for var in $othervar, but how would you read a string character by character.

Thanks in Advance,
AJ Allmendinger

There's surely a more elegant way to do this, but if you have only 4 fields
you can do it with cut:

var1=`cut -d',' -f1 $string`
var2=`cut -d',' -f2 $string`

and so on (the cut command cuts a string into fields delimited by the character
you provide with the -d option).
(the symbols ` surrounding the cut commands are backquotes, they don't
show properly on my browser)

You can set IFS=,
However setting IFS can cause problems with other programs.

Another way:

while read a b c d 
do
    print $a $b $c $d
done <`awk ' BEGIN { FS=, }
        { for(i=1;i<NF;i++) {printf " %s", i } printf "\n" }
      '  datafilename `  

In ksh, use:

#!/usr/bin/ksh
IFS=', <tab>'             #in place of <tab> insert actual tab char
string=data1,data2,data3,data4
echo $string | read d1 d2 d3 d4
echo $d1 $d2 $d3 $d4

This is a duplicate post and violates rule 4:

Here is the link for the other thread.

I have merged the threads.

Hope this helps

str=data1,data2,data3,data4,data5 ## as many as you want

echo $str|awk -F"," '
BEGIN {
i=0;
}
{
for(i=0;i<NF;i++) {
arr [i]= $i;
printf("%d\n", i);
printf("%s\n", arr[i]);
}
}
END {
}'

For reading strings char by char, you will find multiple awk functions, just have a look at man pages for awk

Using an array in bash...

#!/usr/bin/bash

var="data1,data2,data3,data4"
eval $(echo $var|awk -v RS=, '{printf "myArray[%d]=%s\n", NR, $1}')

echo Number of elements in array: ${#myArray[*]}
echo First element is: ${myArray[1]}

Or the set built-in in ksh...

#!/usr/bin/ksh

var="data1,data2,data3,data4"
oldIFS=$IFS
IFS=,
set $var
IFS=$oldIFS

echo Number of positional parameters: $#
echo First parameter is: $1