【问题标题】:How to compare four columns in a csv with awk?如何将csv中的四列与awk进行比较?
【发布时间】:2020-09-02 09:39:38
【问题描述】:

这是How to compare two columns of two csv files with awk?的后续问题。

我有两个 csv 文件需要与一列进行比较。

我的member.csv 文件如下所示:

ID|lastName|firstName|pubID
01|Lastname01|Firstname01|pubID01
02|Lastname02|Firstname02|pubID02
03|Lastname03|Firstname03|pubID03

第二个文件check-ID.csv 看起来像:

Lastname01|Name01|pubID01|Hash01
Lastname02|Name02|pubID02|Hash02a
LastnAme0X|Name03|pubID03|Hash03
Lastname04|Name04|pubID04|Hash04
Lastname02b|Name02|pubID02|Hash02b
Lastname01|Name01|pubID01|Hash01b

--> Lastname04 不在我的member.csv 中!

我想要检查check-ID.csv 第一列的值是否等于member.csv 中第二列的值,或者check-ID.csv 第四列的值是否等于第三列的值在member.csv

我的尝试是

awk 'BEGIN{  FS="|"} FNR==NR{  a[$2]; b[$4]; next }($1 in a  || $3 in b) ' member.csv check-ID.csv  | sort -t'|' -k1

但显然我没有得到正确的条件。

我希望得到过滤和排序的输出,因此只有成员会像这样列出:

Lastname01|Name01|pubID01|Hash01
Lastname01|Name01|pubID01|Hash01b
Lastname02|Name02|pubID02|Hash02a
Lastname02b|Name02|pubID02|Hash02b
LastnAme0X|Name03|pubID03|Hash03

任何帮助表示赞赏!

【问题讨论】:

    标签: awk


    【解决方案1】:

    您能否尝试仅使用所示示例进行跟踪、编写和测试。

    awk '
    BEGIN{
      FS="|"
    }
    {  gsub(/\r/,"")  }
    FNR==NR{
      a[$2]
      b[$4]
      next
    }
    ($1 in a) || ($3 in b)
    ' members.csv  check-ID.csv |
    sort -t'|' -k1
    

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

    awk '                              ##Starting awk program from here.
    BEGIN{                             ##Starting BEGIN section of this program from here.
      FS="|"                           ##Setting field separator as | here.
    }
    {  gsub(/\r/,"")  }                ##Globally substituting all control M characters in all lines.
    FNR==NR{                           ##Checking condition if FNR==NR which will be TRUE when members.csv is being read.
      a[$2]                            ##Creating array a with index of 2nd field.
      b[$4]                            ##Creating array b with index of 4th field here.
      next                             ##next will skip all further statements from here.
    }
    ($1 in a) || ($3 in b)             ##For check-ID.csv Input_file checking condition if either 1st field is present in a OR 3rd field is present in b then print that line.
    ' members.csv  check-ID.csv |      ##Mentioning Input_file names here.
    sort -t'|' -k1                     ##Sending output of awk code to sort command and sorting it by first field with setting field separator as | for all lines.
    

    【讨论】:

    • @LukasCB,对我来说效果很好。您能否通过在两个文件上执行cat -v Input_file 来检查您的 Input_files 是否有控制 M 字符,然后告诉我?
    • 除了一些“元音变音”之外,文件看起来很好,我看不到控制 M 字符。我的实际成员文件中的 pubID 在第 6 列,但我将 b[$4] 更改为 b[$6] 进行测试。
    • @LukasCB,恕我直言,答案总是仅按照所示示例给出。您的示例在成员文件中显示其第 2 和第 4 个字段,在其他文件中显示第 1 和第 3 个字段。如果您的实际文件中的字段编号不同,请相应地更改它们,这应该会飞。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多