将文件1的一个字段与awk中的file2的其他字段进行比较

时间:2015-04-19 03:24:05

标签: bash shell awk

我有两个文件文件1和文件2.我想看到file1的第一列并转到file2中的那个行号。之后我将file1的$ 2与file2的$ 6进行比较。如果匹配则打印"纠正ans"。我想使用awk执行此操作。

FILE1.TXT

1,B
3,C
2,A

FILE2.TXT

Html,WeB,title,tech,Laravel,B
Html,WeB,title,tech,Laravel,D
Html,WeB,title,tech,Laravel,C

Output.txt的

Question  1 is correct
Question 3 is correct
Question 2 is incorrect

我试过这样做。

awk -F[","] 'NR==FNR{n=$1;b=$2}
  {if( NR==$1 && $6==b){printf "Question n is        correct "}
  else { printf "Question n is incorrect"}}' myfile rahulque

2 个答案:

答案 0 :(得分:1)

$ awk -F, 'FNR==NR{ans[NR]=$6;next} {print "Question",$1,"is",((ans[$1]==$2)?"":"in")"correct";}' file2.txt file1.txt
Question 1 is correct
Question 3 is correct
Question 2 is incorrect

如何运作

  • FNR==NR{ans[NR]=$6;next}

    对于列出的第一个文件file2.txt的每一行,我们将正确答案$6存储在数组ans中,其中包含行号NR,钥匙。然后,我们告诉awk跳过其余命令并跳转到next行。

  • print "Question",$1,"is",((ans[$1]==$2)?"":"in")"correct"

    对于第二个列出的文件file1.txt的每一行,我们打印问题$1的答案是否与数组a中指定的正确答案匹配。

    更详细地说,让我们看一下三元语句:

    (ans[$1]==$2)?"":"in"
    

    如果ans[$1]==$2,答案是正确的。在这种情况下,三元语句返回一个空字符串。如果答案不正确,则三元语句返回字符串in。三元语句返回的字符串放在字符串correct的前面,以形成所需的单词。

答案 1 :(得分:0)

我总是发现awk令人困惑,所以如果我找到这个问题的解决方案,我会避免awk所有人在一起,只写一个像...这样的shell脚本。

#!/bin/sh

sort file1.txt | cut -d, -f2 > /tmp/file1.cut
cut -d, -f6 file2.txt > /tmp/file2.cut

count=0
while read -r a && read -r b <&3
do
        count=`expr $count + 1`
        if [ $a == $b ]
        then
                echo  "Question $count is correct"
        else
                echo  "Question $count is incorrect"
        fi
done < /tmp/file1.cut 3< /tmp/file2.cut

...这似乎适用于您提供的示例数据。

$ cat file1.txt
1,B
3,C
2,A
$ cat file2.txt
Html,WeB,title,tech,Laravel,B
Html,WeB,title,tech,Laravel,D
Html,WeB,title,tech,Laravel,C
$ ./correct.sh
Question 1 is correct
Question 2 is incorrect
Question 3 is correct
$ cat correct.sh
#!/bin/sh

sort file1.txt | cut -d, -f2 > /tmp/file1.cut
cut -d, -f6 file2.txt > /tmp/file2.cut

count=0
while read -r a && read -r b <&3
do
        count=`expr $count + 1`
        if [ $a == $b ]
        then
                echo  "Question $count is correct"
        else
                echo  "Question $count is incorrect"
        fi
done < /tmp/file1.cut 3< /tmp/file2.cut

我确定有更好的方法可以做到这一点,比如使用awk,但我认为shell脚本方法更灵活。例如,如果您想计算错误和正确答案的数量。

相关问题