代码之家  ›  专栏  ›  技术社区  ›  as7951

Awk脚本,用于在一定条件下在两个文件中查找、匹配和复制值

  •  0
  • as7951  · 技术社区  · 6 年前

    需要您的帮助以awk编写以下查询的代码。
    有两个文件。 如果第1列(documenttype)中的值为INV,而supplytype(column2)为CAN,则从第3列(documentnumber)中取出相应的值, 并在文件2的第2列(follon doc)中找到该值(documentnumber),如果找到,则从文件2中针对该documentnumber(follon doc)提取列1(predecessr)的值,并将从文件1的第4列(originaldocumentnumber)中的文件2的第1列(predecessr)中找到的值粘贴到文件1的第4列(originaldocumentnumber)中

    对于ex-

    如果我们在文件1中有documentnumber 420075416,documenttype为INV,supplytype为CAN,那么我们可以看到documentnumber(420075416)在文件2的第4行和第2列(follon doc)中存在,因此,如果在文件2中可用,则从第1列(predecessr)中针对该documentnumber(420075416)选择值(430071501),并替换或粘贴到文件1的第4列

    文件1

    documenttype    supplytype  documentnumber  originaldocumentnumber
    INV              CAN        420075416        656565665
    INV              CAN        429842808   
    INV              BRB        429842808         85858585
    INV              CAN        430071605   
    RER              CAN        430071609
    

    文件2

    Predecessr  FollOn doc
    420075200   430071605
    429842808   430071609
    429842807   429842808
    430071501   420075416
    429842807   429842808
    

    输出文件

    documenttype    supplytype  documentnumber  originaldocumentnumber
    INV              CAN       420075416            430071501
    INV              CAN       429842808            429842807
    INV              BRB       429842808            85858585
    INV              CAN       430071605            420075200
    RER              CAN       430071609
    

    只能写下面的代码,但感到困惑,无法继续

    if '(NR==FNR)&&(FNR>1)&&($1==INV && $2==CAN){ar[$3]=NR;next}
        {for(i in ar){if
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   James Brown    6 年前

    好吧,除了吸引眼球的间距之外,这应该可以做到:

    $ awk '
    NR==FNR {                              # process first file
        a[$2]=$1                           # hash, 2nd column as key, 1st its value
        next                               # next record
    }                                      # second file:
    $1=="INV" && $2=="CAN" && ($3 in a) {  # INV, CAN and 3rd column in hash
        $4=a[$3]                           # set 4th column value from the hash
        # flag=1                           # see comment
    }
    {
        $1=$1                              # rebuild the record 
        print                              # output
    }
    #END {
    #    if(!flag) 
    #        system("cat " FILENAME)
    # }
    ' file2 file1                         # mind the order
    documenttype supplytype documentnumber originaldocumentnumber
    INV CAN 420075416 430071501
    INV CAN 429842808 429842807
    INV BRB 429842808 85858585
    INV CAN 430071605 420075200
    RER CAN 430071609
    

    你可以通过管道 column -t 为了让它看起来更好:

    $ awk ... | column -t 
    documenttype  supplytype  documentnumber  originaldocumentnumber
    INV           CAN         420075416       430071501
    ...