MST
星途 面试题库

面试题:Bash脚本中动态处理不同编码文件转换

编写一个Bash脚本,它能够接收用户输入的源文件名、源文件编码以及目标文件编码。脚本要使用iconv命令将源文件从指定的源编码转换为目标编码,并将结果输出到一个新文件,新文件名为源文件名加上目标编码后缀(例如`test_目标编码.txt`)。请考虑错误处理,比如源文件不存在时给出提示。
15.3万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 检查参数个数是否正确
if [ $# -ne 3 ]; then
    echo "Usage: $0 <source_file> <source_encoding> <target_encoding>"
    exit 1
fi

source_file=$1
source_encoding=$2
target_encoding=$3

# 检查源文件是否存在
if [ ! -f $source_file ]; then
    echo "Source file $source_file does not exist."
    exit 1
fi

# 生成目标文件名
target_file="${source_file%.*}_$target_encoding.${source_file##*.}"

# 使用iconv进行编码转换
iconv -f $source_encoding -t $target_encoding $source_file -o $target_file

# 检查iconv命令是否成功执行
if [ $? -eq 0 ]; then
    echo "Encoding conversion successful. Output file: $target_file"
else
    echo "Encoding conversion failed."
fi