0

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.

3 Answers 3

4
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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

2 Comments

+1 Exactly what I had. You should always quote your variables
@steve Not quite, you're comparing the wrong column to $GROUP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.