简体   繁体   English

用数据填充Shell脚本数组

[英]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: 下面,我从/ etc / group中提取一些数据并将其保存在另一个文件中,然后打印每一个项目:

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. 但是,我不想将数据提取到文件中,而是提取到数组中。

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

The assignment with the parentheses indicates that $members is an array. 带括号的赋值表示$members是一个数组。 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. 原始的awk命令已包含在$(...) ,并添加了冒号,因此,如果文件中包含groupgroup1 ,并且您查找group ,则也不会获得group1的数据。 Of course, if you wanted both entries, then you drop the colon I added. 当然,如果您都想要这两个条目,则可以删除我添加的冒号。

j=0
for i in `awk '{ print $0 }' $FILE`
do
  arr[$j] = $i
  j=`expr $j + 1`
done 
arr=($(awk -F: -v g=$GROUP '$1 == g { gsub(/,/,"\n",$4) ; print $4 }' /etc/group))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM