首页 > 解决方案 > 如果来自一个文件的字符串并在另一个文件中搜索,如何读取列表?

问题描述

我正在尝试从一个文件中读取字符串列表并将其与第二个文件的第一列进行比较并打印整行。

我试过grep -f file1.txt file2.txt但它比较整行中的字符串并打印它,我只想与第一列进行比较并打印该行

例如。

file1.txt

34534
67823
41400

file2.txt 

41400 41440 52705 10254 20239 39975 40075 71022 82531
43897 41420 71104 10252 20243 41400 71065 83830
34534 41440 83203 10266 20255 40086 70262 84476
78314 22540 60000 10250 20247 40083 82432
67823 41440 70000 10246 20231 39646 40092 71052 83531

输出是:

41400 41440 52705 10254 20239 39975 40075 71022 82531
43897 41420 71104 10252 20243 <b>41400</b> 71065 83830
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531

以下是预期输出:

34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531
41400 41440 52705 10254 20239 39975 40075 71022 82531

标签: shelltextgrep

解决方案


我会使用awk:

$ awk 'NR==FNR{a[$0];next}($1 in a)' file1 file2

输出:

41400 41440 52705 10254 20239 39975 40075 71022 82531
34534 41440 83203 10266 20255 40086 70262 84476
67823 41440 70000 10246 20231 39646 40092 71052 83531

解释:

$ awk '        # using awk
NR==FNR {      # process the first file
    a[$0]      # hash words to a array
    next       # move to proces next word if any left
}
($1 in a)      # if the first word of the second file record was hashed, output
' file1 file2

更新

file1.txt使用顺序打印:

$ awk '
NR==FNR {
    a[$1]=a[$1] (a[$1]==""?"":RS) $0   # catenate records based on $1
    next
}
{
    print a[$0]
}' file2.txt <(tac file1.txt)

上面的记录更改顺序演示了 bu 颠倒file1.txt使用rev. 以其他顺序输出:

67823 41440 70000 10246 20231 39646 40092 71052 83531
34534 41440 83203 10266 20255 40086 70262 84476
41400 41440 52705 10254 20239 39975 40075 71022 82531

推荐阅读