这应该很容易。我会使用 Python,因为我是 Python 粉丝。大纲:
你真的不能就地编辑文件......嗯,如果每个新变量名的长度总是与旧名完全相同,我想你可以。但是为了便于编程和运行时的安全,最好总是编写一个新的输出文件,然后删除原始文件。这意味着在运行它之前您至少需要 20 GB 的可用磁盘空间,但这应该不是问题。
这是一个 Python 程序,它展示了如何做到这一点。我使用您的示例数据制作测试文件,这似乎有效。
#!/usr/bin/python
import re
import sys
try:
fname_idmap, fname_in, fname_out = sys.argv[1:]
except ValueError:
print("Usage: remap_ids <id_map_file> <input_file> <output_file>")
sys.exit(1)
# pattern to match an ID, only as a complete word (do not match inside another id)
# match start of line or whitespace, then match non-period until a period is seen
pat_id = re.compile("(^|\s)([^.]+).")
idmap = {}
def remap_id(m):
before_word = m.group(1)
word = m.group(2)
if word in idmap:
return before_word + idmap[word] + "."
else:
return m.group(0) # return full matched string unchanged
def replace_ids(line, idmap):
return re.sub(pat_id, remap_id, line)
with open(fname_idmap, "r") as f:
next(f) # discard first line with column header: "oldId newIds"
for line in f:
key, value = line.split()
idmap[key] = value
with open(fname_in, "r") as f_in, open(fname_out, "w") as f_out:
for line in f_in:
line = replace_ids(line, idmap)
f_out.write(line)