我需要一种快速方法来匹配 AWK 中的值,我有 250k 个值需要搜索。
我正在做这样的事情:
#list with 250k numbers instead of four
number_list="9998532001 9998536052 9998543213 9998544904"
if ( index(number_list,substr($5,9)) )
{printf "Value: %s\n",$5;}
对于更快的搜索有什么建议吗?
最佳答案
如果您要搜索的子字符串在目标字符串中具有一致的长度和位置(例如最后 6 位数字),那么您可以将列表预处理为数组,然后就可以开始了。
预处理步骤(可能在 BEGIN
目标中)
n=split(numbers_list,a," "); # Rip in input sting into pieces
for ( num in a ) {
key=substr(a[num],length(a[num])-6,6); # Get the last six digits
# Error processing (i.e. collision handling) should go here
list[key]=a[num];
}
然后当你需要进行查找时
i=list[substr($5,9)] # i is now the full number associated with the key
只有当您进行多次查找时,这才是胜利,因为在预处理期间您仍然需要支付遍历整个列表(实际上是两次)的成本。
请注意,与整个数字的精确匹配符合已知长度和位置的子字符串,只需使用 key=a[num]
(这看起来很有趣,并导致上述代码的一些简化,但我相信你能弄清楚)。
如果您正在查找任何数字中任何出现的substring($5,9)
,则此方法将不起作用,您必须迭代每次n
。
关于linux - AWK 快速值搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7518292/