#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 --input <файл|-> [--top N] [--min-length N] [--stopwords файл] [--output файл]" } input="-" top=25 min_length=3 stopwords="" output="" while [[ $# -gt 0 ]]; do case "$1" in --input) input="${2:-}"; shift 2 ;; --top) top="${2:-}"; shift 2 ;; --min-length) min_length="${2:-}"; shift 2 ;; --stopwords) stopwords="${2:-}"; shift 2 ;; --output) output="${2:-}"; shift 2 ;; -h|--help) usage; exit 0 ;; *) echo "Неизвестный аргумент: $1" >&2; usage >&2; exit 2 ;; esac done if [[ "$input" != "-" && ! -f "$input" ]]; then echo "Файл не найден: $input" >&2 exit 2 fi if [[ -n "$stopwords" && ! -f "$stopwords" ]]; then echo "Файл стоп-слов не найден: $stopwords" >&2 exit 2 fi if ! [[ "$top" =~ ^[0-9]+$ ]] || ! [[ "$min_length" =~ ^[0-9]+$ ]]; then echo "--top и --min-length должны быть числами" >&2 exit 2 fi tmp_dir="$(mktemp -d)" trap 'rm -rf -- "$tmp_dir"' EXIT if [[ "$input" == "-" ]]; then cat > "$tmp_dir/input.txt" else cp -- "$input" "$tmp_dir/input.txt" fi upper="АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ" lower="абвгдеёжзийклмнопрстуфхцчшщъыьэюя" ascii_upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ" ascii_lower="abcdefghijklmnopqrstuvwxyz" sed -e "y/${upper}/${lower}/" -e "y/${ascii_upper}/${ascii_lower}/" "$tmp_dir/input.txt" > "$tmp_dir/lower.txt" grep -oE '[[:alnum:]_-]+' "$tmp_dir/lower.txt" > "$tmp_dir/words.txt" || true sed -E 's/^-+//; s/-+$//' "$tmp_dir/words.txt" | grep -vE '^$|^[0-9]+$' > "$tmp_dir/cleaned.txt" || true if [[ -n "$stopwords" ]]; then tr -d '\r' < "$stopwords" | sed -e "y/${upper}/${lower}/" -e "y/${ascii_upper}/${ascii_lower}/" | grep -oE '[[:alnum:]_-]+' > "$tmp_dir/stop.txt" || true grep -vFxf "$tmp_dir/stop.txt" "$tmp_dir/cleaned.txt" > "$tmp_dir/filtered.txt" || true else cp "$tmp_dir/cleaned.txt" "$tmp_dir/filtered.txt" fi grep -E "^.{$min_length,}$" "$tmp_dir/filtered.txt" > "$tmp_dir/final.txt" || true sort "$tmp_dir/final.txt" | uniq -c | sort -rn | head -n "$top" > "$tmp_dir/top.txt" if [[ ! -s "$tmp_dir/top.txt" ]]; then echo "Слова не найдены" >&2 exit 1 fi if [[ -n "$output" ]]; then cp -- "$tmp_dir/top.txt" "$output" echo "Результат: $output" else cat "$tmp_dir/top.txt" fi