【问题标题】:Match First Column from First File to Line in Second File Then Insert Last Column of Matched Line from Second File as New First Column in First File将第一个文件的第一列与第二个文件中的行匹配,然后将第二个文件中匹配行的最后一列插入第一个文件中的新第一列
【发布时间】:2021-10-16 20:08:08
【问题描述】:

我有以下两个文件:

file1:

1,foo,bar,etc
2,bar,etc,aaa
3,.......,abc

file2:

1,rand,xyz,lastcol1
aaa,bbb,ccc,2,ddd,lastcol2
xyz,3,lastcol3

对于 file1 (1,2,3) 中的每个第一列,如果它与 file2 中的一行匹配,则该行的最后一列应成为 file1 的新第一列。

newfile:

lastcol1,1,foo,bar,etc
lastcol2,2,bar,etc,aaa
lastcol3,3,.......,abc

【问题讨论】:

  • 您所说的查找匹配行的命令将仅在 2 个文件之间找到 1 个匹配行,因为这两个文件之间唯一的共同 $1 是 1 但您的示例输入/输出显示所有行都应该2个文件之间的匹配。你的例子是错的还是你的代码错了?请edit您的问题来解决任何问题。您现有的代码 'NR==FNR{c[$1]++;next};c[$1]' 不是如何在 2 个文件中找到匹配的 $1s 顺便说一句,这是:'NR==FNR{c[$1];next}; $1 in c'
  • 删除了不正确的部分。
  • 您删除了自己解决问题的尝试。不要这样做,因为这是让你的问题被否决和关闭的可靠方法,因为这个论坛的存在是为了帮助人们编写代码,而不是为人们编写代码,所以这里没有代码的问题是 OT。见How to Ask。把你的代码放回去,明确你对在两个文件之间的比较中应该使用哪些字段的要求。

标签: awk command-line


【解决方案1】:

看看这个awk 程序:

BEGIN {
    FS=","
}
FNR == 1 {
    # because there are more than one file on input 
    nb_file++
}
nb_file == 1 {
    # first file memorization in hash table
    # the key is the first field
    hash[$1]=$0
    next
}
nb_file == 2 {
    # second file treatment
    # for all keys in hash table from first file...
    for (k in hash) {
        i = 1
        found = 0
        # for all columns in the second file line
        while (i <= NF) {
            # if field value equals to key name
            if ($i == k) {
                # print last field value, coma, and first file line is hash table
                print $NF "," hash[k]
                # stop when found
                found = 1
                break
            }
            i++
        }
        if (found == 1) {
            # stop when found
            break
        }
    }
}

这样使用:

$ awk -f trt.awk file1 file2
lastcol1,1,foo,bar,etc
lastcol2,2,bar,etc,aaa
lastcol3,3,.......,abc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多