用于替换平面文件中文本的脚本


Script to replace text in a flat file

我有一个平面文件(csv 分隔),其中包含 60 个值,需要用 60 个不同的新值替换。

Original_Value1 ---> New_Value1
Original_Value2 ---> New_Value2
Original_Value3 ---> New_Value3
Original_Value4 ---> New_Value4

....到 60。

该文件有超过 200k 个条目,其中包含需要更改的 60 个值。实现这一目标的最有效方法是什么?

假设

1) 新旧值的长度可能不同

2)您不知道哪些行包含要提前更改的值

使用 fgetcsv() 逐行遍历文件检查该行中的字段,进行必要的替换。使用 fputcsv() 将行写回其他文件

下面是示例代码:

$input  = 'input.txt';
$output = 'output.txt';
if ($fpin = fopen($input, 'r')) {
  if ($fpout = fopen($output, 'a')) {
    while ($data = fread($fpin, 1024)) {
      fwrite($fpout, your_replacement_function($data));
    }
    fclose($fpout);
  }
  fclose($fpin);
}

查看fgetcsv以逐行读取文件并添加一些代码以查看每行是否包含要替换的字符串。

阅读每一行后,执行您需要执行的操作并将其写入新文件。您可以使用fputcsv来编写 CSV。最后删除旧文件。

也许有人知道编辑文件中间的方法?我认为这是不可能的。

Perl. 至少这是我的建议,应该能够在一行中做到这一点......类似的东西

open( IN, " < filename.csv ");
open( OUT, " > output.csv ");
while (<IN>) { # reads in each line of the file
   $line =~ s/Original_Value1/New_Value1/gi;  # g is for global, i is to ignore case
   $line =~ s/Original_Value2/New_Value2/gi;  # g is for global, i is to ignore case
   $line =~ s/Original_Value3/New_Value3/gi;  # g is for global, i is to ignore case
   # ... continue to your values... probably a better way of doing this from a file, but this is quick and dirty, and should work
   print OUT $line; # prints out $line to the output file.
}
close(IN);
close(OUT);

无论如何,这已经很接近了,我已经有一段时间没有写perl了,它可能会被擅长PERL高尔夫的人优化为几个字符...... =)