【问题标题】:Extract lines in file1 starting with a specific word given in file2提取 file1 中以 file2 中给出的特定单词开头的行
【发布时间】:2015-05-11 14:35:24
【问题描述】:

我有一个文件“file1”,其中包含以下行:

643 2   3   4   5
6433    2   3   4   5
64  2   3   4   5
1234    2   3   4   5
1240    2   3   4   5
12  2   3   4   5

我想从中提取第一个单词包含在文件 2 中的所有行,例如:

12
64

因此,最终的结果应该是:

12  2   3   4   5
64  2   3   4   5

在 bash 中,我认为我必须使用循环来检查文件 2 中的每个单词,但我不知道提取文件 1 中包含确切单词的行的命令。

例如,使用:

sed -n '/^64/p' file1

我明白了:

643 2 3 4 5 6433 2 3 4 5 64 2 3 4 5

这是不正确的,因为我只想要一行: 64 2 3 4 5

您知道执行此操作的 bash 方法(sed、grep、awk 或 python)吗?

【问题讨论】:

    标签: bash awk sed grep extraction


    【解决方案1】:

    我会说:

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

    即:

    NR == FNR {    # while processing the first file (file2)
      a[$1] = 1    # remember what values you saw
      next         # do nothing else
    }
    a[$1]          # after that (while processing file1): print those whose first
                   # field was seen in the pass over file2.
    

    【讨论】:

      【解决方案2】:

      你可以使用:

      awk 'NR==FNR{a[$1]; next} $1 in a' file2 file1
      64  2   3   4   5
      12  2   3   4   5
      

      【讨论】:

      • awk '$1 in a;a[$1]' file2 file1 , awk 'a[$1]++' file2 file1
      • 这里为什么需要;a[$1]
      • 这样就创建好了?不明白你的意思?
      • 您是否尝试过上面给出的awk 命令?您得到的输出与我在回答中显示的不同吗?
      【解决方案3】:

      我认为您可以尝试使用 grep -w 更准确:

       -w    Searches for the expression as a word as if surrounded
             by \< and \>.
      

      所以你可以试试:

      grep -w 64 file1
      

      在 Solaris 10 上运行

      【讨论】:

        【解决方案4】:

        要使用 grep,还要在搜索文件中的模式中添加一个锚点:

        grep -wf <(sed 's/^/^/' file2) file1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-28
          • 1970-01-01
          • 1970-01-01
          • 2020-05-23
          • 1970-01-01
          • 2022-10-12
          相关资源
          最近更新 更多