将行值与列值匹配,并重命名该行

时间:2014-07-08 18:17:17

标签: sorting awk match

我有一个包含以下标题的文件:

文件1:

location, nameA, nameB, nameC

和第二个文件格式为:

File2:

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

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

谢谢!

1 个答案:

答案 0 :(得分:0)

如果你的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