【问题标题】:unix - find unmatch of lines in 2 text fileunix - 在 2 个文本文件中查找不匹配的行
【发布时间】:2017-12-21 10:09:09
【问题描述】:

我正在尝试进行匹配和不匹配练习..我确实尝试过尝试 grep 和 diff...但它只匹配整行....是否可以匹配文件中的行,如下所示?

如果我有 2 个文件:

文件 1:

cat_cute    
green_apple_sour    
red_bean_big    
red_pepper_three    
ginger_yellow

文件 2:

cat    
green_apple    
red_pepper    
papaya

输出:

(file1)
red_bean_big    
ginger_yellow            
(file2)    
papaya

在发布此问题之前,我已成功尝试以下方法。我很抱歉没有在我的第一篇文章中列出这个。 我将文件 2 设置为目标匹配。对于文件 1,我使用 TCL 删除所有不需要的形容词。然后我得到新文件 1

新文件 1:

cat    
green_apple    
red_bean    
red_pepper    
ginger

然后我申请了:

grep -Fxvf newfile1 file2

我得到了我想要的输出。

我只是想知道是否有其他方法可以仅使用 grep 命令而不使用 TCL regsub 进程。我确实尝试过 awk、comm 和 grep。仅当整行匹配 100% 时才匹配。

谢谢。

【问题讨论】:

  • 如果 file1 中有一行 dogs_eat_papaya ,该行是否应该出现在输出中?
  • grep -v -f file2 file1 似乎就是你所需要的。
  • 不...只是完全匹配前面而已。
  • 所以假设后面可以是任何数字。 dog1 dog56 dog135 在我的文件 1 中;文件2中的狗。是否有可能输出:全部匹配。 ?
  • 我已投票决定关闭此问题,因为它似乎是请求推荐工具或解决方案,而不是请求帮助您自己的代码。这使您的问题与 StackOverflow 无关。如果该评估不正确,并且您确实需要帮助编写自己的代码,那么请add your work so far to your question,我将撤回我的近距离投票。

标签: unix awk grep diff comm


【解决方案1】:

我没有正确理解您的问题。顺便说一句,您可以通过awk 轻松完成。

awk -F'_' 'FILENAME=="file2.txt" {a[$1$2]=$1$2} FILENAME=="file1.txt" {if(!(a[$1] || a[$1$2])) {print}}' file2.txt file1.txt

它将打印:

red_bean_big    
ginger_yellow

对于 File2 您可以颠倒顺序(稍作更改)。

awk -F'_' 'FILENAME=="file1.txt" {a[$1]=$1} FILENAME=="file2.txt" {if(!(a[$1])) {print}}' file1.txt file2.txt

上面的命令将打印:

papaya

我希望我清楚地理解了您的问题。如果您需要其他内容,请在下方评论。

【讨论】:

    【解决方案2】:

    在 awk 中:

    $ awk '
    NR==FNR {                  # first file
        a[$1]                  # hash entries to a
        next                   # next record
    }
    {                          # second file
        for(i in a)            # for each record go thru the whole of a
            if(i~$1||$1~i) {   # see if there is a match
                delete a[i]    # del if
                next           # and skip to next record
            }                  
        b[$1]                  # else store entry to b
    }
    END {                      # in the end
        print "(file1)" 
        for(i in a) 
            print i            # output a and
        print "(file2)"
        for(i in b) 
            print i            # b entries
    }' file1 file2
    (file1)
    ginger_yellow
    red_bean_big
    (file2)
    papaya
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-25
      • 2020-03-03
      • 2016-11-23
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      相关资源
      最近更新 更多