1

inputfile : records.txt

100,Surender,CTS
101,Kumar,TCS
102,Raja,CTS
103,Vijay,TCS

I want to store the first column from each record and store that in to array .

I wrote the below script

id_array=();
while read  -a my_line ;

do

  id_array+=(${my_line[0]})

  done < /home/user/surender/linux/inputfiles/records.txt;

 echo ${id_array[0]}
 echo ${id_array[1]}
 echo ${id_array[2]}
 echo ${id_array[3]}

My expected output is

100
101
102
103

But as Per above code i get the below output

 100,Surender,CTS
 101,Kumar,TCS
 102,Raja,CTS
 103,Vijay,TCS

I dont know where to specify the respective delimiter(comma) in above script.

Need some Help on this..

Surender Raja
  • 3,553
  • 8
  • 44
  • 80

2 Answers2

3

Replace the line:

while read  -a my_line ;

With:

while IFS=',' read  -a my_line ;

That will split the lines into an array using the delimiter ,.

1

There are many methods to get the first field. Cut is very intuitive, although this is probably not the most efficient code:

id_array+=(echo $my_line | cut -d ',' -f 1)

explanation:

  • -d ',' : delimiter is ,
  • -f 1 : take the first field

in a related answer you can find a more efficient way, setting the internal field separator (IFS) to ,...

Community
  • 1
  • 1
Chris Maes
  • 35,025
  • 12
  • 111
  • 136