Read all the fields in a Loop

Hi,

I have a line like
A,B,C,D,E,F

and I need to loop for 6 times (as many number of fields in above line) and in every loop I need to get the value into a variable. How can I do it?

Pls advise!

Thanks much!!

while IFS=',' read var
do
   echo $var
done < infile

Note: Replace infile with your file name which has line like A,B,C,D,E,F

Hi

$ cat file
A,B,C,D,E,F
$ sed 's/,/\n/g' file | while read var
> do
>   echo $var
> done

Guru.

1 Like

Sorry It does NOT work - Simply prints the line as it is (with commas) - Am using bash.

Thanks anyway!!

---------- Post updated at 12:50 PM ---------- Previous update was at 12:50 PM ----------

Works great - Thanks much!!

My bad, that was incorrect way of using it. Correction:-

while IFS=',' read v1 v2 v3 v4 v5 v6
do
   echo "$v1 $v2 $v3 $v4 $v5 $v6"
done < infile

But I guess you won't prefer this since it is fetching values into multiple variables.

I won't use it as it uses multiple variables and also there can be ANY number of fields.

Thanks

OLDIFS="$IFS"
IFS="," # Split unquoted variables on comma instead of spaces

VAR="a,b,c,d,e,f,g"

for X in $VAR
do
        echo $X
done

IFS="$OLDIFS"
$ cat x.dat
A,B,C,D,E,F
$
$
$ cat x
#!/bin/ksh

# Save current IFS.
OLD_IFS=$IFS

# Set IFS to the separator in the file.
IFS=","

# Read the entire file into the array.  Assumes 1 line in the file.
set -A letter_array $( < x.dat )

# Find out how many elements were read in.
ctr=${#letter_array
[*]}

# Print the entire array.
print "\nThe whole array: [${letter_array[@]}]"
print "$ctr elements\n"

# Print the elements in reverse order.
while (( $ctr > 0 )); do
  print "Element $ctr: ${letter_array[${ctr}-1]}"
  (( ctr=$ctr-1 ))
done

# reset IFS.  Good practice, but not really needed since we exit right away.
IFS=$OLD_IFS
exit 0

$ ./x

The whole array: [A B C D E F]
6 elements

Element 6: F
Element 5: E
Element 4: D
Element 3: C
Element 2: B
Element 1: A
$