【问题标题】:How to compare a file w.r.t a keyword file and replace mismatch strings of column 3 with correct string in column 3 of keyword file如何比较文件 w.r.t 关键字文件并将第 3 列的不匹配字符串替换为关键字文件第 3 列中的正确字符串
【发布时间】:2020-11-19 20:03:15
【问题描述】:

我想在 keyword_file 中搜索 search_file 的每一行并打印一个 output_file 用提取的正确字符串替换该行的不正确字符串来自 keyword_file。此外,如果缺少第 3 列的条目很少,则应警告用户,这些条目在 keyword_file 中不存在并且在 search_file 中具有(例如,“ggg coms”在文件)

注意,这里 keyword_file 可能包含与 search_file 不同的行数。例如: 搜索文件

aaa coms 123
bbb coms 234
ccc 
ddd coms 456
eez coms 789
fkk coms 987
ggg coms   
hhh coms 989
....

keyword_file

aaa coms 789
bbb coms 234
ccc coms 878
ddd coms 456
ttt coms 654 
eee coms 789

输出

aaa coms 789
bbb coms 234
ccc coms 878
ddd coms 456
eez coms 789
fkk coms 987
hhh coms 989
....

我尝试了以下 awk 命令,但它无法在 输出 中保留 search_file 的第 1 列条目。

awk 'FNR==NR{a[$1]=$0} FNR!=NR&&a[$1]{print $1,$2,$3}' search_file keyword_file

非常感谢您的帮助:)

【问题讨论】:

    标签: linux shell perl awk sed


    【解决方案1】:

    您能否仅根据所示示例尝试以下、编写和测试。

    awk '
    {
      key=$1
    }
    FNR==NR{
      a[key]=$3
      next
    }
    (key in a){
      $0=key OFS $2 OFS a[key]
    }
    1
    '  keyword_file  search_file
    

    说明:为上述添加详细说明。

    awk '                                ##Starting awk program from here.
    {
      key=$1                             ##Run this command on each line of Input_file and create variable key with value of 1st field.
    }
    FNR==NR{                             ##Checking condition if FNR==NR which will be TRUE when keyword_file is being read.
      a[key]=$3                          ##Creating array a with index key and value of 3rd field here.
      next                               ##next will skip all further statements from here.
    }
    (key in a){                          ##Checking condition if key is present in array a then do following.
      $0=key OFS $2 OFS a[key]           ##Setting value of key OFS 2nd field OFS array a value with index key here.
    }
    1                                    ##1 will print edited/non-edited values for all lines.
    '  keyword_file  search_file         ##Mentioning Input_file names here.
    

    为什么 OP 的代码不起作用:您很接近,您只打印了 Input_files 中第一个和第二个字段共同的行,所以我所做的是:而检查两个 Input_files 中字段是否通用的条件,然后使用新的最后一个值重新创建该行,然后通过提及 1 打印当前(已编辑/未编辑)行。

    【讨论】:

    • 非常感谢您的解决方案。它像你提到的那样工作。我更新了我的问题以正确匹配我的场景。使用您的解决方案,我无法获得“ccc”信息。你能帮我解决这个问题吗?
    • 非常感谢您的解决方案。采纳答案!只是一个小问题,我无法得到“ccc coms 878”,而是得到“ccc 878”,有什么办法可以得到吗?
    • @coolcom,你展示的样本很好,我看到ccc coms 878 不知道为什么它不适合你,它对我来说很好。
    • @RavinderSingh13,这取决于我拥有的 linux 版本吗?因为我无法获得“ccc coms 878”。代码的哪一部分正在处理这个问题,请您在这里指导我。我是 Linux 新手。
    • @coolcom,当然你可以从你身边检查,为你的指导欢呼添加了解释。
    猜你喜欢
    • 2015-01-09
    • 2019-03-17
    • 2021-09-07
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多