Excel 类似 vlookup 的命令行函数或工具?
Excel vlookup-like command line function or tool?
我有一个包含 200 万多行文本的源文件,如下所示:
388708091|347|||||0010.60|N01/2012|
388708101|348|||||0011.60|N01/2012|
388708101|349|||||0012.60|N01/2012|
388719001|348|||||0010.38|M05/2013|
388719001|349|||||0011.38|M05/2013|
我想用如下所示的地图映射和替换第二列(其值类似于 347,348,349 等):
346 309
347 311
348 312
349 313
350 314
351 315
352 316
请注意,虽然地图是二维的,但有 100 多行。
将源文件第二列中的数据替换为目标地图的最有效命令行方式是什么?
awk
似乎是完成这项工作的工具:
awk 'NR == FNR { a[] = ; next } FNR == 1 { FS = "|"; OFS = FS; [=10=] = [=10=] } { = a[] } 1' mapfile datafile
代码的工作原理如下:
NR == FNR { # while processing the first file (mapfile)
a[] = # remember the second field by the first
next # do nothing else
}
FNR == 1 { # at the first line of the second file (datafile):
FS = "|" # start splitting by | instead of whitespace
OFS = FS # delimit output the same way as the input
[=11=] = [=11=] # force resplitting of this first line
}
{ # for all lines in the second file:
= a[] # replace the 2nd field with the remembered value for that key
}
1 # print the line
警告: 这假定数据文件第二列中的每个值在映射文件中都有相应的条目;那些没有的将被替换为空字符串。如果此行为不可取,请替换
{ = a[] }
和
{ if( in a) { = a[] } else { = "something else" } }
我不清楚在这种情况下会发生什么。
我有一个包含 200 万多行文本的源文件,如下所示:
388708091|347|||||0010.60|N01/2012|
388708101|348|||||0011.60|N01/2012|
388708101|349|||||0012.60|N01/2012|
388719001|348|||||0010.38|M05/2013|
388719001|349|||||0011.38|M05/2013|
我想用如下所示的地图映射和替换第二列(其值类似于 347,348,349 等):
346 309
347 311
348 312
349 313
350 314
351 315
352 316
请注意,虽然地图是二维的,但有 100 多行。
将源文件第二列中的数据替换为目标地图的最有效命令行方式是什么?
awk
似乎是完成这项工作的工具:
awk 'NR == FNR { a[] = ; next } FNR == 1 { FS = "|"; OFS = FS; [=10=] = [=10=] } { = a[] } 1' mapfile datafile
代码的工作原理如下:
NR == FNR { # while processing the first file (mapfile)
a[] = # remember the second field by the first
next # do nothing else
}
FNR == 1 { # at the first line of the second file (datafile):
FS = "|" # start splitting by | instead of whitespace
OFS = FS # delimit output the same way as the input
[=11=] = [=11=] # force resplitting of this first line
}
{ # for all lines in the second file:
= a[] # replace the 2nd field with the remembered value for that key
}
1 # print the line
警告: 这假定数据文件第二列中的每个值在映射文件中都有相应的条目;那些没有的将被替换为空字符串。如果此行为不可取,请替换
{ = a[] }
和
{ if( in a) { = a[] } else { = "something else" } }
我不清楚在这种情况下会发生什么。