Найти и заменить текст в файлах
Ищет строку во всех текстовых файлах папки и сохраняет изменённые копии в отдельный каталог.
Что делает скрипт
Скрипт обходит указанную папку, пропускает двоичные файлы и считает каждое вхождение. По умолчанию результат пишется в папку text-out, а исходники остаются нетронутыми. Для правки на месте нужен явный флаг --in-place, при этом рядом создаётся резервная копия .bak.
- Флаг --in-place меняет исходные файлы, но оставляет копии .bak.
Быстрый старт
python find_replace.py --path ./docs --find old --replace new
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python find_replace.py --path ./docs --find old --replace new --dry-runpython find_replace.py --path notes.md --find 2025 --replace 2026 --in-placepython find_replace.py --path . --find draft --replace final --glob '*.md'
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
find_replace.py
#!/usr/bin/env python3
"""Поиск и замена строки в текстовых файлах."""
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
def is_binary(path: Path) -> bool:
try:
return b"\0" in path.read_bytes()[:4096]
except OSError:
return True
def collect_files(root: Path, pattern: str, out_dir: Path) -> list[Path]:
if root.is_file():
return [root]
files = []
for path in sorted(root.rglob(pattern)):
if not path.is_file():
continue
if out_dir == path or out_dir in path.parents:
continue
files.append(path)
return files
def destination(source: Path, root: Path, out_dir: Path) -> Path:
relative = source.relative_to(root) if root.is_dir() else Path(source.name)
target = out_dir / relative
target.parent.mkdir(parents=True, exist_ok=True)
return target
def main() -> int:
parser = argparse.ArgumentParser(description="Найти и заменить строку в файлах")
parser.add_argument("--path", type=Path, required=True, help="Файл или папка")
parser.add_argument("--find", required=True, help="Что искать")
parser.add_argument("--replace", required=True, help="На что заменить")
parser.add_argument("--glob", default="*", help="Маска файлов, например '*.txt'")
parser.add_argument("--encoding", default="utf-8", help="Кодировка файлов")
parser.add_argument("--output-dir", type=Path, default=Path("text-out"), help="Куда писать копии")
parser.add_argument("--in-place", action="store_true", help="Править файлы на месте")
parser.add_argument("--dry-run", action="store_true", help="Только показать совпадения")
args = parser.parse_args()
root = args.path.expanduser().resolve()
if not root.exists():
parser.error(f"Путь не найден: {root}")
if args.find == "":
parser.error("Пустая строка поиска")
if args.in_place and args.dry_run:
parser.error("Флаги --in-place и --dry-run несовместимы")
out_dir = args.output_dir.expanduser().resolve()
files = collect_files(root, args.glob, out_dir)
total_files = 0
total_hits = 0
for source in files:
if is_binary(source):
continue
try:
text = source.read_text(encoding=args.encoding)
except UnicodeDecodeError:
print(f"Пропуск (не {args.encoding}): {source}")
continue
except OSError as error:
print(f"Пропуск {source}: {error}")
continue
hits = text.count(args.find)
if hits == 0:
continue
total_files += 1
total_hits += hits
if args.dry_run:
print(f"{source}: {hits} совпадений")
continue
updated = text.replace(args.find, args.replace)
if args.in_place:
backup = source.with_name(source.name + ".bak")
shutil.copy2(source, backup)
source.write_text(updated, encoding=args.encoding)
print(f"Изменён {source}, копия {backup.name}")
else:
target = destination(source, root, out_dir)
if target.resolve() == source.resolve():
print(f"Пропуск, выходной путь совпадает с входным: {source}")
continue
if target.exists():
print(f"Перезапись {target}")
target.write_text(updated, encoding=args.encoding)
print(f"Сохранено {target}")
print(f"Файлов с совпадениями: {total_files}, вхождений: {total_hits}")
if not args.in_place and not args.dry_run and total_files:
print(f"Результаты в папке {out_dir}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.