Bash脚本批量读取时间列表查询轮盘赌发牌员的实现问题
批量处理Bash脚本实现方案
核心思路
用while read循环逐行读取输入文件,拆分每行的MMDD日期和完整时间字段,调用grep查询对应调度文件,将结果追加到输出文件。
完整脚本示例
假设输入文件为timestamps.txt,输出文件为dealer_results.txt:
#!/bin/bash # 清空输出文件(需要覆盖旧结果则保留,追加则删除此行) > dealer_results.txt # 逐行读取输入文件,拆分日期和时间 while read -r mmdd full_time; do schedule_file="${mmdd}_Dealer_schedule.txt" # 检查调度文件是否存在,避免无效查询 if [ -f "$schedule_file" ]; then grep "$full_time" "$schedule_file" >> dealer_results.txt else echo "警告:未找到文件 $schedule_file,跳过此行" >> dealer_results.txt fi done < timestamps.txt
常见错误修复方案
1. Xargs处理带空格时间失败
xargs默认按空格拆分参数,会把05:00:00 AM拆成两个独立参数,导致grep匹配错误。可改用按行处理的方式:
xargs -I {} sh -c 'mmdd=$(echo {} | cut -d" " -f1); time=$(echo {} | cut -d" " -f2-); grep "$time" "${mmdd}_Dealer_schedule.txt"' < timestamps.txt >> dealer_results.txt
但while read写法更直观,更适合处理带空格的字段。
2. 数组拆分时间出错
如果用数组存储行内容,需确保时间部分作为整体元素:
#!/bin/bash > dealer_results.txt while read -r -a line_parts; do mmdd="${line_parts[0]}" # 从索引1开始拼接所有元素,保留完整时间 full_time="${line_parts[@]:1}" schedule_file="${mmdd}_Dealer_schedule.txt" [ -f "$schedule_file" ] && grep "$full_time" "$schedule_file" >> dealer_results.txt done < timestamps.txt
3. 变量未正确引用
脚本中必须用双引号包裹变量(如grep "$full_time" "$schedule_file"),否则时间中的空格会被解析为多个参数,导致grep行为异常。
测试建议
- 先取输入文件的一行测试单条命令,确认匹配逻辑正确:
grep "05:00:00 AM" 0310_Dealer_schedule.txt
- 运行脚本前,注释掉
>> dealer_results.txt,改为终端输出,排查错误信息。 - 保留文件存在检查,避免因文件缺失导致脚本中断。
内容的提问来源于stack exchange,提问作者localpawn
相关产品推荐
相关产品推荐

