Bash:在嵌套循环中读取两个文件中的相同行

时间:2014-06-04 15:44:47

标签: bash file nested

我试图从几个文件中计算置信区间:其中包含带有平均值的行,其他包含带有值的行(每行一个)。我试图从包含平均值的文件中读取一行,并从另一个文件中读取所有行(因为我必须进行一些计算)。这就是我所做的(当然它不起作用):

parameters="some value to move from a file to another one"

while read avg; do 
    for row in mypath/*_${parameters}*.dat; do
        for value in $( awk '{ print $2; }' ${row}); do

    read all the lines in first_file.dat (I need only the second column)
            read the first line in avg.dat
            combine data and calculate the confidence interval      

    done
    done
done < avg.dat

** 文件avg.dat(不一定是100行) **

0.99
2.34
5.41
...
...
2.88

mypath中的

** firstfile.dat(100行) **

0 13.77
1 2
2 63.123
3 21.109
...
...
99 1.05

mypath中的

** secondfile.dat(100行) **

0 8.56
1 91.663
2 19
3 0
...
...
99 4.34

avg.dat的第一行是指mypath中的firstfile.dat,avg.dat的第二行是指mypath中的secondfile.dat等等。所以,在上面的例子中,我必须这样做使用.99(来自avg.dat)进行一些计算,其中包含firstfile.dat第二列中的所有数字。与2.34和secondfile.dat相同。

我无法实现我的目标,因为当我完成阅读mypath中的文件时,我找不到切换到avg.dat中下一行的方法。相反,我读了avg.dat中的第一行和mypath中的所有文件,然后是avg.dat中的第二行,再次是mypath中的所有文件等等...你能帮我找一个解决方案吗?谢谢大家!

1 个答案:

答案 0 :(得分:1)

在bash中我会这样做:

exec 3<avg.dat
shopt -s extglob
for file in !(avg).dat; do
    read -u 3 avg
    while read value; do
        # do stuff with $value and $avg
    done < <(cut -f 2 -d " " "$file")
done
exec 3<&-   # close the file descriptor