【问题标题】:find same value in 2 differents column from differents files在来自不同文件的 2 个不同列中找到相同的值
【发布时间】:2016-08-27 13:43:36
【问题描述】:

我有 2 个文件:

file1.txt:

1 A bla 9232
1 B tesfs 3049
1 C blof 4054
2 D dkeeez 3049
2 E eor 4042
3 F foaer 4024

file2.txt:

A
B
E

预期输出,file3.txt:

1 A bla 9232
1 B tesfs 3049
2 E eor 4042

输出只是来自 file1 的行,它在第 2 列中包含与 file2 中相同的值。

在file2.txt中,每一行都是唯一的,但你可以有:

A
AA
AAee
B
...

我尝试使用 grep -Ff file2.txt file1.txt 但 file3.txt 中仍有一行在 file2.txt 中不存在 解决方案可以在行内或在 shell 脚本中,我尝试使用“awk”和 shell 脚本,但没有结果...

【问题讨论】:

    标签: bash shell awk scripting grep


    【解决方案1】:

    你可以使用awk命令:

    awk 'FNR==NR{a[$1]; next} $2 in a' file2.txt file1.txt
    

    在第一次迭代中,我们将来自file2.txt 的所有值存储到数组a 中。在第二步白色迭代 file1.txt 中,我们检查第 2 列是否在数组 a 中并打印出来。

    输出:

    1 A bla 9232
    1 B tesfs 3049
    2 E eor 4042
    

    【讨论】:

    • 是的,它运行良好,即使没有尝试过的列表(我没有在我的问题中指定有时不能尝试该文件)
    【解决方案2】:

    这是join 擅长的一件事,前提是您的输入已排序(file1.txt 在字段 2 上,file2.txt 在字段 1 上 - 您的示例显示已排序的输入,但如果您的实际输入是't,你必须在 join 工作之前修复它):

    join -1 2 -2 1 -o 1.1,1.2,1.3,1.4 file1.txt file2.txt
    

    【讨论】:

    • 这个解决方案也很完美,但我没有指定文件有时不能排序!
    【解决方案3】:

    我喜欢 anubbhava 的 awk 解决方案。这是使用 grep 的替代解决方案:

    # Add word anchors before and after each word in file2.txt
    sed 's/^/\\b/;s/$/\\b/' file2.txt > temp.txt  
    
    grep -f temp.txt file1.txt
    rm temp.txt
    

    文件 temp.txt 如下所示:

    \bA\b
    \bB\b
    \bE\b
    

    接下来,我们将使用该 temp.txt 文件作为搜索词并获得所需的结果。

    【讨论】:

      【解决方案4】:

      grep + awk 版本:

      # This will grep the first column of file2.txt in file1.txt. 
      
      grep "`awk '{print $1}' file2.txt`" file1.txt
      1 A bla 9232
      1 B tesfs 3049
      2 E eor 4042
      

      grep + cut 版本:

      # This will grep the first column of file2.txt in file1.txt. 
      
      grep "`cut -d' ' -f1 file2.txt`" file1.txt
      
      1 A bla 9232
      1 B tesfs 3049
      2 E eor 4042
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多