0
  • 输入文件1:file1.txt
    MH=919767, 918975
    DL= 919922
    HR=919891,919394,919812
    KR=919999,918888

  • 输入文件2:file2.txt
    aec,919922783456,a5,b3,,,asf
    abc,918975583456,a1,b1,,,abf
    aeci,919998546783,a2,b4,,,wsf

  • 输出文件
    aec,919922783456,a5,b3, DL ,,asf
    abc,918975583456,a1,b1, MH ,,abf
    aeci,919998546783,a2,b4, NOMATCH ,,wsf

  • 笔记

    • 需要在Input file1.txt - 2nd field with "=" separted) 中比较电话号码( Input file2.txt - 2nd field - 仅初始 6 位) 。如果电话号码的初始 6 位匹配,则 OUTPUT 应包含从文件(输入文件 1)到第 5 字段输出的 2 位代码
    • File1.txt 具有用于多个电话号码首字母的单个代码(例如 MH)。
4

2 回答 2

1

尝试类似:

awk '
  NR==FNR{
    for(i=2; i<=NF; i++) A[$i]=$1
    next
  } 
  {
    $5="NOMATCH"
    for(i in A) if ($2~"^" i) $5=A[i]
  } 
  1
' FS='[=,]' file1 FS=, OFS=, file2
于 2013-02-24T07:51:45.897 回答
1

如果您有GNU awk,请尝试以下操作。像这样运行:

awk -f script.awk file1.txt file2.txt

内容script.awk

BEGIN {
     FS="[=,]"
     OFS=","
}

FNR==NR {
    for(i=2;i<=NF;i++) {
        a[$1][$i]
    }
    next
}

{
    $5 = "NOMATCH"
    for(j in a) {
        for (k in a[j]) {
            if (substr($2,0,6) == k) {
                $5 = j
            }
        }
    }
}1

或者,这是单线:

awk -F "[=,]" 'FNR==NR { for(i=2;i<=NF;i++) a[$1][$i]; next } { $5 = "NOMATCH"; for(j in a) for (k in a[j]) if (substr($2,0,6) == k) $5 = j }1' OFS=, file1.txt file2.txt

结果:

aec,919922783456,a5,b3,DL,,asf
abc,918975583456,a1,b1,MH,,abf
aeci,919998546783,a2,b4,NOMATCH,,wsf

如果您有“旧” awk,请尝试以下操作。像这样运行:

awk -f script.awk file1.txt file2.txt

script.awk 的内容:

BEGIN {
     # set the field separator to either an equals sign or a comma
     FS="[=,]"
     # set the output field separator to a comma
     OFS=","
}

# for the first file in the arguments list
FNR==NR {
    # loop through all the fields, starting at field two
    for(i=2;i<=NF;i++) {

        # add field one and each field to a pseudo-multidimensional array
        a[$1,$i]
    }

    # skip processing the rest of the code
    next
}


# for the second file in the arguments list
{
    # set the default value for field 5
    $5 = "NOMATCH"

    # loop though the array
    for(j in a) {

        # split the array keys into another array
        split(j,b,SUBSEP)

        # if the first six digits of field two equal the value stored in this array
        if (substr($2,0,6) == b[2]) {

            # assign field five 
            $5 = b[1]
        }
    }

# return true, therefore print by default
}1

或者,这是单线:

awk -F "[=,]" 'FNR==NR { for(i=2;i<=NF;i++) a[$1,$i]; next } { $5 = "NOMATCH"; for(j in a) { split(j,b,SUBSEP); if (substr($2,0,6) == b[2]) $5 = b[1] } }1' OFS=, file1.txt file2.txt

结果:

aec,919922783456,a5,b3,DL,,asf
abc,918975583456,a1,b1,MH,,abf
aeci,919998546783,a2,b4,NOMATCH,,wsf
于 2013-02-24T09:02:54.027 回答