user1812379
user1812379

Reputation: 847

Filling a shell script array with data

I want to extract some data from a file and save it in an array, but i don't know how to do it.

In the following I'm extracting some data from /etc/group and save it in another file, after that I print every single item:

awk -F: '/^'$GROUP'/ { gsub(/,/,"\n",$4) ; print $4 }' /etc/group > $FILE

for i in `awk '{ print $0 }' $FILE`
   do
     echo "member: "$i" "
   done 

However, I don't want to extract the data into a file, but into an array.

Upvotes: 0

Views: 1198

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753605

members=( $(awk -F: '/^'$GROUP':/ { gsub(/,/,"\n",$4) ; print $4 }' /etc/group) )

The assignment with the parentheses indicates that $members is an array. The original awk command has been enclosed in $(...), and the colon added so that if you have group and group1 in the file, and you look for group, you don't get the data for group1 too. Of course, if you wanted both entries, then you drop the colon I added.

Upvotes: 4

Barmar
Barmar

Reputation: 780852

arr=($(awk -F: -v g=$GROUP '$1 == g { gsub(/,/,"\n",$4) ; print $4 }' /etc/group))

Upvotes: 2

Peter Gluck
Peter Gluck

Reputation: 8236

j=0
for i in `awk '{ print $0 }' $FILE`
do
  arr[$j] = $i
  j=`expr $j + 1`
done 

Upvotes: 2

Related Questions