#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 <входной файл> [выходной файл] [--leading] [--in-place]" } input="" output="" leading=0 in_place=0 while [[ $# -gt 0 ]]; do case "$1" in --leading) leading=1; shift ;; --in-place) in_place=1; shift ;; -h|--help) usage; exit 0 ;; --*) echo "Неизвестный флаг: $1" >&2; usage >&2; exit 2 ;; *) if [[ -z "$input" ]]; then input="$1" elif [[ -z "$output" ]]; then output="$1" else echo "Лишний аргумент: $1" >&2 exit 2 fi shift ;; esac done if [[ -z "$input" || ! -f "$input" ]]; then echo "Укажите существующий входной файл" >&2 exit 2 fi if [[ "$in_place" -eq 1 && -n "$output" ]]; then echo "С --in-place выходной файл указывать нельзя" >&2 exit 2 fi if [[ -n "$output" && "$output" == "$input" ]]; then echo "Выходной файл совпадает с входным, используйте --in-place" >&2 exit 2 fi sed_args=(-e 's/[[:blank:]]*$//') if [[ "$leading" -eq 1 ]]; then sed_args+=(-e 's/^[[:blank:]]*//') fi run_sed() { sed -E "${sed_args[@]}" -- "$1" } if [[ "$in_place" -eq 1 ]]; then backup="${input}.bak" cp -p -- "$input" "$backup" tmp="$(mktemp "${input}.XXXXXX")" trap 'rm -f -- "$tmp"' EXIT run_sed "$input" > "$tmp" if cmp -s -- "$input" "$tmp"; then echo "Изменений нет" rm -f -- "$tmp" rm -f -- "$backup" trap - EXIT else mv -- "$tmp" "$input" trap - EXIT echo "Файл обновлён, копия: $backup" fi elif [[ -n "$output" ]]; then run_sed "$input" > "$output" echo "Результат: $output" else run_sed "$input" fi