Привести переводы строк к одному виду
Определяет CRLF, LF и CR, показывает смешанные файлы и конвертирует их в выбранный формат.
Что делает скрипт
Скрипт читает файлы в двоичном виде, чтобы точно посчитать переводы строк и не потерять BOM. Поддерживаются форматы lf, crlf и cr, а результат по умолчанию пишется в text-out. Для замены исходников нужен --in-place с резервной копией .bak.
- С --in-place исходные файлы заменяются, рядом остаются копии .bak.
Быстрый старт
python line_endings.py --path ./src --to lf --glob '*.txt'
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python line_endings.py --path notes.txt --to crlfpython line_endings.py --path ./scripts --to lf --glob '*.sh' --dry-runpython line_endings.py --path ./docs --to lf --in-place
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
line_endings.py
#!/usr/bin/env python3
"""Определение и смена переводов строк."""
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
def detect(data: bytes) -> dict[str, int]:
crlf = data.count(b"\r\n")
lf = data.count(b"\n") - crlf
cr = data.count(b"\r") - crlf
return {"crlf": crlf, "lf": lf, "cr": cr}
def convert(data: bytes, target: str) -> bytes:
normalized = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
if target == "crlf":
return normalized.replace(b"\n", b"\r\n")
if target == "cr":
return normalized.replace(b"\n", b"\r")
return normalized
def collect(root: Path, pattern: str, out_dir: Path) -> list[Path]:
if root.is_file():
return [root]
return [
path
for path in sorted(root.rglob(pattern))
if path.is_file() and out_dir not in path.parents
]
def main() -> int:
parser = argparse.ArgumentParser(description="Привести переводы строк к одному виду")
parser.add_argument("--path", type=Path, required=True, help="Файл или папка")
parser.add_argument("--to", choices=["lf", "crlf", "cr"], default="lf", help="Целевой формат")
parser.add_argument("--glob", default="*", 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}")
out_dir = args.output_dir.expanduser().resolve()
files = collect(root, args.glob, out_dir)
changed = 0
for source in files:
try:
data = source.read_bytes()
except OSError as error:
print(f"Пропуск {source}: {error}")
continue
counts = detect(data)
kinds = [name for name, value in counts.items() if value]
if not kinds:
continue
if len(kinds) > 1:
print(f"Смешанные переводы: {source} {counts}")
updated = convert(data, args.to)
if updated == data:
continue
changed += 1
if args.dry_run:
print(f"Будет изменён {source}: {kinds} -> {args.to}")
continue
if args.in_place:
backup = source.with_name(source.name + ".bak")
shutil.copy2(source, backup)
source.write_bytes(updated)
print(f"Изменён {source}, копия {backup.name}")
else:
relative = source.relative_to(root) if root.is_dir() else Path(source.name)
target = out_dir / relative
if target.resolve() == source.resolve():
print(f"Пропуск, выходной путь совпадает с входным: {source}")
continue
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(updated)
print(f"Сохранено {target}")
print(f"Файлов изменено: {changed}")
if args.dry_run:
print("Это предпросмотр. Для записи уберите --dry-run.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.