bash exec命令使while循环太多?

时间:2018-09-26 22:10:27

标签: bash unix

我有2个文本文件1.txt和2.txt。

1.txt由用制表符分隔的名称和ID组成,如下所示:

Doe,John    123456
Smith,Jack  234678
Green,George987987
West,Mae    444555

2.txt由ID和成绩组成,也由制表符分隔,如下所示:

234678  B
123456  A+
444555  B+
987987  C+

我想从1.txt中的每一行获取id,在2.txt中搜索匹配项,然后将与该数字关联的名称和等级输出到新文件中。

预期输出:

Doe,John A+
Smith,Jack B
Green,GeorgeC+
West,Mae B+

所以我做的是:

>namegrades.txt

exec < $1 #read from 1.txt
while read line
do       #store the name and the id for the current line
    number=$(echo "$line" | cut -d$'\t' -f 2); 
    name=$(echo "$line" | cut -d$'\t' -f 1);
    echo $name # used to test
    exec < $2   #take input from 2.txt
    while read line
    do #store the grade and check the current line in file for a matching id
        grade=$(echo "$line" | cut -d$'\t' -f 2);
        check=$(echo "$line" | grep -c $number)
        echo $check    
        if [ $check == 1 ]; then  #if there is a match echo to new file
    #echo "$name    $grade" >> namegrades.txt
            echo hello   #used to test
        fi
    done < $2
done < $1

当我运行代码时,我得到的输出是:

Doe,John
1
hello
0
0
0
123456
1
hello
0
0
0
123456
1
hello
0
0
0

重复无穷大。我是unix的新手,也不知道如何解决这个问题,对您有所帮助。

1 个答案:

答案 0 :(得分:0)

这个怎么样。
通过IFS在while循环中读取每个文件。将1.txt的ID1与2.txt的id2进行比较,如果相等,则将其附加到第三文件。

这确实吸收了一些讨论,并将其放在一起作为解决方案。

while IFS=$'\t' read -r name id1
do
  while IFS=$'\t' read -r id2 grade
  do
    if [ "$id1" == "$id2" ]; then
      printf '%s\t%s\n' "$name" "$grade"
    fi
  done < /tmp/2.txt
done < /tmp/1.txt |tee -a /tmp/3.txt

结果

Doe,John     A+
Smith,Jack   B
Green,George C+
West,Mae     B+
相关问题