简体   繁体   English

用于创建数组的Shell脚本

[英]Shell script for creating arrays

I want for every number in a unix file run a grep with the exact content in a second file and put the results I find in an array. 我想为unix文件中的每个数字在第二个文件中运行grep,并将其确切内容放入数组中。

The first file (words) is in this form: 第一个文件(单词)的格式如下:

a
b
c
d

and the second one (frequencies) contains 第二个(频率)包含

f 3
b 8
d 4
v 2
a 5
c 2

so I want to create arrays that contain the following: 所以我想创建包含以下内容的数组:

[a 5]
[b 8]
[c 2]
[d 4]

help much appreciated! 帮助非常感谢!

You need to reset the IFS variable (the delimeter used for arrays). 您需要重置IFS变量(用于数组的分度符)。

OIFS=$IFS #save original
IFS=','
arr=($(awk 'FNR==NR {a[$1]=$2;next} a[$1] {print $1,a[$1]","}' second first))
IFS=$OIFS

echo ${arr[0]}
a 5
echo ${arr[1]}
b 8
echo ${arr[*]}
a 5
b 8
c 2
d 4

a solution using join could be: 使用join的解决方案可能是:

sort second > second.sort
IFS=','
arr=($(join first second.sort | tr '\n' ','))
rm second.sort

output: 输出:

echo ${arr[0]}
a 5

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

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