尝试用文心一言写了个 shell 脚本,一字未改,直接运行,运行结果正确。的确可以提高工作效率。
输入的问题如下:
请按照以下要求编写一个shell脚本。
1. 编写一个函数,函数名是cnvfile。其输入是一个文件名。首先用chardetect检验这个文件的字符集。将输出保存到变量csname中。如果 csname 中包含子字符串“GB2312”或者“GBK”或者“GB18030”,则将这个文件从 GB2312转换为带BOM的UTF-8文件,转换结果覆盖原始文件,否则不做转换,直接退出函数。
2. 递归的对给定目录下的所有扩展名为*.h 或者*.cpp的文件,运行函数cnvfile
文心一言的回答如下:
要编写一个满足您要求的shell脚本,首先确保您的系统上已经安装了chardetect
和iconv
这两个工具。chardetect
用于检测文件的字符集,而iconv
用于进行字符集转换。
以下是按照您的要求编写的shell脚本:
#!/bin/bash
# 函数定义:cnvfile
# 参数:文件名
function cnvfile {
local file="$1"
local csname=$(chardetect "$file")
if [[ "$csname" == *"GB2312"* ]] || [[ "$csname" == *"GBK"* ]] || [[ "$csname" == *"GB18030"* ]]; then
echo "转换文件: $file"
# 使用iconv进行GB2312转带BOM的UTF-8
iconv -f GB2312 -t UTF-8//TRANSLIT "$file" -o "$file"
else
echo "文件: $file 不需要转换"
fi
}
# 递归遍历目录下的所有*.h和*.cpp文件,并调用cnvfile函数
function process_files {
local dir="$1"
for file in "$dir"/*.h "$dir"/*.cpp "$dir"/*.txt; do
if [ -f "$file" ]; then
cnvfile "$file"
fi
done
for subdir in "$dir"/*; do
if [ -d "$subdir" ]; then
process_files "$subdir"
fi
done
}
# 主程序开始
if [ $# -eq 0 ]; then
echo "请提供一个目录作为参数。"
exit 1
fi
process_files "$1"