ABC公司员工账户CSV规范化bash脚本修复与实现需求
修复后的员工账户处理脚本(task1.sh)
原脚本存在以下问题:
- 未接收命令行参数指定输入文件路径,硬编码了
input_file - 未处理重复邮箱需追加location_id的核心需求
- 末尾的diff对比逻辑无意义(生成的文件必然与原文件存在格式差异)
以下是修复并优化后的脚本:
#!/bin/bash # 检查输入参数是否存在 if [ $# -ne 1 ]; then echo "用法: $0 <accounts.csv路径>" exit 1 fi input_file="$1" output_file="accounts_new.csv" # 检查输入文件是否存在 if [ ! -f "$input_file" ]; then echo "错误: 文件 $input_file 不存在" exit 1 fi # 清空或创建输出文件 > "$output_file" # 写入表头 head -n 1 "$input_file" >> "$output_file" # 用关联数组跟踪邮箱出现次数 declare -A email_counts # 处理数据行 tail -n +2 "$input_file" | while IFS=',' read -r id location_id name title email department; do # 格式化姓名:每个单词首字母大写,其余小写 formatted_name=$(echo "$name" | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2)); print}') # 提取名的首字母和全姓氏小写(兼容姓名含多个单词的情况,取最后一个单词为姓) first_initial=$(echo "$formatted_name" | awk '{print tolower(substr($1,1,1))}') surname=$(echo "$formatted_name" | awk '{print tolower($NF)}') base_email="${first_initial}${surname}@abc" # 处理重复邮箱 ((email_counts["$base_email"]++)) if [ "${email_counts["$base_email"]}" -gt 1 ]; then formatted_email="${base_email%@abc}${location_id}@abc" else formatted_email="$base_email" fi # 写入输出文件 echo "$id,$location_id,$formatted_name,$title,$formatted_email,$department" >> "$output_file" done echo "新文件已生成: $output_file"
关键修复说明
- 命令行参数支持:脚本现在接收一个参数作为输入文件路径,启动方式为
./task1.sh ./accounts.csv,同时增加了参数检查和文件存在性校验 - 姓名格式化优化:改用awk循环处理姓名中的每个单词,确保不管姓名是2个还是多个单词,都能实现首字母大写、其余小写的格式
- 重复邮箱处理:通过关联数组
email_counts跟踪每个基础邮箱的出现次数,当次数大于1时,在邮箱前缀后追加location_id - 冗余逻辑移除:删除了原脚本中无意义的diff对比,改为直接提示文件生成成功
内容的提问来源于stack exchange,提问作者Zero One
相关产品推荐
相关产品推荐

