【问题标题】:match a row value to a column value, and rename the row将行值与列值匹配,并重命名该行
【发布时间】:2014-08-29 14:40:06
【问题描述】:

我有一个文件头如下:

文件 1:

location, nameA, nameB, nameC

第二个文件格式为:

文件2:

ID_number, names            
101, nameA            
102, nameB                      
103, nameC          

我想将 File1 中的行名与 File2 的第 2 列中的行名匹配,如果匹配,则将标题中的名称替换为 ID 号。所以最后,生成的文件会是:

文件 1:

location, 101, 102, 103

我大部分时间都在尝试使用 awk 来做这件事,但我无法让它产生任何东西,而且我不知道如何让它做我想要的最后一部分。

awk -F "," '{print $2}'  file2.csv | while read i; do awk 'NR=1;{for (j=0;j<=NF;j++) {if ($j == $i) printF $j; }}' file1.csv;done > test.csv

这是一个包含数千列和行的非常大的文件,所以我只是在这里提出了我的问题中文件的简化版本。

谢谢!

【问题讨论】:

    标签: sorting awk match


    【解决方案1】:

    如果您的 csv 字段没有嵌入逗号,这应该可以工作。它还假设两个文件都有一个标题行。

    awk '
    
      BEGIN { FS=","; OFS=", " }
    
      FNR == 1 {       # if it is the header line
        if (NR != 1)     # if it is the second file
          print            # print it
        next             # go to next line of file
      }
    
      { gsub(/ +/, "") }  # compress spaces
    
      NR == FNR {         # if it is the first file
        a[$2] = $1        # save the info
        next              # go to next line of file
      }
    
      {
        $2=a[$2]; $3=a[$3]; $4=a[$4]  # swap names
        print                         # print line
      }
    
    ' file2.csv file1.csv
    

    测试文件:

    file1.csv

    location, nameA, nameB, nameC
    Earth, Chuck, Edward, Bob
    The Moon, Bob, Doris, Al
    

    file2.csv

    ID_number, names
    101, Al
    102, Bob
    103, Chuck
    104, Doris
    105, Edward
    

    输出:

    location, nameA, nameB, nameC
    Earth, 103, 105, 102
    TheMoon, 102, 104, 101
    

    【讨论】:

    • 你能告诉我 a[$2] 函数在做什么吗?我还想更改标题,而不是将“Chuck”、“Edward”和“Bob”更改为 103,105,102-nameA、nameB 和 nameC 将更改为 103、105,102。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 2022-01-23
    • 1970-01-01
    • 2021-05-19
    • 2022-07-06
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多