【发布时间】:2011-12-22 13:42:44
【问题描述】:
我想对某些文本执行许多查找和替换操作。我有一个 UTF-8 CSV 文件,其中包含要查找的内容(在第一列中)和替换它的内容(在第二列中),从最长到最短排列。
例如:
orange,fruit2
carrot,vegetable1
apple,fruit3
pear,fruit4
ink,item1
table,item2
原始文件:
"I like to eat apples and carrots"
生成的输出文件:
"I like to eat fruit3s and vegetable1s."
但是,我想确保如果文本的一部分已经被替换,它不会与已经被替换的文本混淆。换句话说,我不希望它看起来像这样(它与蔬菜 1 中的“表”匹配):
"I like to eat fruit3s and vegeitem21s."
目前,我使用这种方法很慢,因为我必须进行两次查找和替换:
(1) 将CSV转换为三个文件,例如:
a.csv b.csv c.csv
orange 0001 fruit2
carrot 0002 vegetable1
apple 0003 fruit3
pear 0004 fruit4
ink 0005 item1
table 0006 item 2
(2) 然后,将file.txt中a.csv中的所有项目替换为b.csv中的匹配列,并在单词周围使用ZZZ以确保以后匹配数字没有错误:
a=1
b=`wc -l < ./a.csv`
while [ $a -le $b ]
do
for i in `sed -n "$a"p ./b.csv`; do
for j in `sed -n "$a"p ./a.csv`; do
sed -i "s/$i/ZZZ$j\ZZZ/g" ./file.txt
echo "Instances of '"$i"' replaced with '"ZZZ$j\ZZZ"' ("$a"/"$b")."
a=`expr $a + 1`
done
done
done
(3) 然后再次运行相同的脚本,但将ZZZ0001ZZZ 替换为来自c.csv 的fruit2。
运行第一个替换大约需要 2 小时,但由于我必须运行此代码两次以避免编辑已替换的项目,因此需要两倍的时间。有没有更有效的方法来运行查找和替换而不对已替换的文本执行替换?
【问题讨论】:
-
您希望用什么语言或技术来做这件事?
-
在 Linux 中。我没有想到任何特定的语言,但我需要确保它可以支持 UTF-8。
-
每个文件有多少行?
-
要编辑的文件和列表各有 100,000 行。
标签: perl bash optimization replace sed