replace function

int replace(
  1. String path,
  2. Pattern existing,
  3. String replacement, {
  4. bool all = false,
})

Implementation

int replace(
  String path,
  Pattern existing,
  String replacement, {
  bool all = false,
}) {
  var changes = 0;
  final tmp = '$path.tmp';
  if (exists(tmp)) {
    delete(tmp);
  }
  touch(tmp, create: true);
  read(path).forEach((line) {
    String newline;
    if (all) {
      newline = line.replaceAll(existing, replacement);
    } else {
      newline = line.replaceFirst(existing, replacement);
    }
    if (newline != line) {
      changes++;
    }

    tmp.append(newline);
  });
  if (changes != 0) {
    move(path, '$path.bak');
    move(tmp, path);
    delete('$path.bak');
  } else {
    delete(tmp);
  }
  return changes;
}