MST
星途 面试题库

面试题:Bash数组与文件处理结合

有一个文本文件,每行包含一个单词。编写Bash脚本,读取该文件内容,将每个单词存入数组,然后对数组进行去重操作,并将去重后的数组元素按字母顺序逆序输出到另一个文件中。同时,脚本需要处理文件不存在等异常情况。
40.5万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

file_path="input.txt"
output_path="output.txt"

# 检查文件是否存在
if [ ! -f "$file_path" ]; then
    echo "文件 $file_path 不存在"
    exit 1
fi

# 读取文件内容到数组
declare -a words
while read -r word; do
    words+=("$word")
done < "$file_path"

# 数组去重
declare -a unique_words
for word in "${words[@]}"; do
    exists=false
    for unique_word in "${unique_words[@]}"; do
        if [ "$word" = "$unique_word" ]; then
            exists=true
            break
        fi
    done
    if [ "$exists" = false ]; then
        unique_words+=("$word")
    fi
done

# 对去重后的数组按字母顺序逆序排序
sorted_unique_words=($(printf '%s\n' "${unique_words[@]}" | sort -r))

# 将逆序排序后的数组输出到文件
printf '%s\n' "${sorted_unique_words[@]}" > "$output_path"