本文目录导读:

Shell 脚本(适用于 Linux 运维、嵌入式环境)
该版本使用纯 Bash 和文本文件存储,无需额外依赖。
#!/bin/bash
# 车辆信息管理脚本 (Vehicle Management System)
# 数据文件路径
DATA_FILE="vehicle_data.txt"
# 初始化:如果文件不存在,创建并写入表头
if [ ! -f "$DATA_FILE" ]; then
echo "车牌号|品牌|车型|颜色|车主|联系电话|购买年份" > "$DATA_FILE"
fi
# 函数:显示菜单
show_menu() {
clear
echo "==============================="
echo " 车辆信息管理系统"
echo "==============================="
echo "1. 添加车辆信息"
echo "2. 查询车辆信息"
echo "3. 修改车辆信息"
echo "4. 删除车辆信息"
echo "5. 显示所有车辆"
echo "6. 统计车辆数量"
echo "0. 退出系统"
echo "==============================="
read -p "请输入您的选择 [0-6]: " choice
}
# 函数:添加车辆
add_vehicle() {
echo "--- 添加新车 ---"
read -p "车牌号 (如: 京A88888): " plate
# 简单检查是否重复
if grep -q "^$plate|" "$DATA_FILE"; then
echo "错误:车牌号 $plate 已存在!"
return
fi
read -p "品牌 (如: 丰田): " brand
read -p "车型 (如: 凯美瑞): " model
read -p "颜色: " color
read -p "车主: " owner
read -p "联系电话: " phone
read -p "购买年份: " year
# 追加到文件
echo "$plate|$brand|$model|$color|$owner|$phone|$year" >> "$DATA_FILE"
echo "车辆添加成功!"
}
# 函数:查询车辆(支持模糊和精确查询)
query_vehicle() {
echo "--- 查询车辆 ---"
echo "1. 按车牌号精确查询"
echo "2. 按车主姓名模糊查询"
echo "3. 按品牌查询"
read -p "请选择查询方式 [1-3]: " qtype
read -p "请输入查询关键字: " keyword
echo "查询结果:"
case $qtype in
1) grep -i "^$keyword|" "$DATA_FILE" | awk -F'|' '{print "车牌: "$1" 品牌: "$2" 车型: "$3" 颜色: "$4" 车主: "$5" 电话: "$6" 年份: "$7}' ;;
2|3) grep -i "$keyword" "$DATA_FILE" | awk -F'|' '{print "车牌: "$1" 品牌: "$2" 车型: "$3" 颜色: "$4" 车主: "$5" 电话: "$6" 年份: "$7}' ;;
*) echo "无效选项" ;;
esac
}
# 函数:修改车辆信息
modify_vehicle() {
echo "--- 修改车辆信息 ---"
read -p "请输入要修改的车牌号: " plate
if [ ! -f "$DATA_FILE" ]; then
echo "数据文件不存在"
return
fi
# 检查是否存在
if ! grep -q "^$plate|" "$DATA_FILE"; then
echo "未找到该车辆!"
return
fi
# 提示新信息(直接覆盖)
echo "请输入新的车辆信息:"
read -p "新品牌: " brand
read -p "新车型: " model
read -p "新颜色: " color
read -p "新车主: " owner
read -p "新电话: " phone
read -p "新购买年份: " year
# 使用 sed 替换整行(注意 Mac 和 Linux sed 差异,这里使用临时文件)
sed -i "/^$plate|/c\\$plate|$brand|$model|$color|$owner|$phone|$year" "$DATA_FILE"
# sed -i 不支持,可采用下文 Python 版本
echo "车辆信息已更新!"
}
# 函数:删除车辆
delete_vehicle() {
echo "--- 删除车辆 ---"
read -p "请输入要删除的车牌号: " plate
if grep -q "^$plate|" "$DATA_FILE"; then
# 用 grep -v 排除该行
grep -v "^$plate|" "$DATA_FILE" > temp.txt && mv temp.txt "$DATA_FILE"
echo "车辆 $plate 已删除!"
else
echo "未找到该车辆!"
fi
}
# 函数:显示所有
list_all() {
echo "--- 所有车辆列表 ---"
awk -F'|' 'NR>1 {printf "%-10s %-10s %-10s %-6s %-10s %-15s %s\n", $1,$2,$3,$4,$5,$6,$7}' "$DATA_FILE"
}
# 函数:统计
stat_vehicles() {
local count=$(awk 'NR>1' "$DATA_FILE" | wc -l)
echo "当前共有 $count 辆车。"
if [ $count -gt 0 ]; then
echo "品牌分布:"
awk -F'|' 'NR>1 {brand[$2]++} END {for (b in brand) print b, brand[b]"辆"}' "$DATA_FILE"
fi
}
# 主循环
while true; do
show_menu
case $choice in
1) add_vehicle ;;
2) query_vehicle ;;
3) modify_vehicle ;;
4) delete_vehicle ;;
5) list_all ;;
6) stat_vehicles ;;
0) echo "感谢使用,再见!"; exit 0 ;;
*) echo "无效选择,请重新输入" ;;
esac
read -p "按回车键继续..." dummy
done
使用方法:
- 保存为
vehicle.sh。 - 运行
chmod +x vehicle.sh && ./vehicle.sh。
Python 脚本(推荐,支持中文友好、数据持久化更安全)
该版本使用 JSON 格式存储,数据结构清晰,支持更复杂的查询。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import sys
from datetime import datetime
DATA_FILE = "vehicle_data.json"
# 初始化数据结构
def load_data():
if not os.path.exists(DATA_FILE):
# 默认数据结构
return []
with open(DATA_FILE, 'r', encoding='utf-8') as f:
try:
return json.load(f)
except json.JSONDecodeError:
print("数据文件损坏,重新初始化。")
return []
def save_data(vehicles):
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(vehicles, f, ensure_ascii=False, indent=4)
def show_menu():
print("\n" + "="*40)
print(" 车辆信息管理系统")
print("="*40)
print("1. 添加车辆信息")
print("2. 查询车辆信息")
print("3. 修改车辆信息")
print("4. 删除车辆信息")
print("5. 显示所有车辆")
print("6. 统计信息")
print("0. 退出系统")
print("="*40)
def add_vehicle(vehicles):
print("\n--- 添加新车 ---")
plate = input("车牌号: ").strip()
# 检查重复
for v in vehicles:
if v['plate'] == plate:
print("错误:车牌号已存在!")
return
brand = input("品牌: ").strip()
model = input("车型: ").strip()
color = input("颜色: ").strip()
owner = input("车主: ").strip()
phone = input("联系电话: ").strip()
year = input("购买年份: ").strip()
# 简单验证年份
if year and not year.isdigit():
print("警告:年份应为数字,已保存。")
vehicle = {
"plate": plate,
"brand": brand,
"model": model,
"color": color,
"owner": owner,
"phone": phone,
"year": year,
"created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
vehicles.append(vehicle)
save_data(vehicles)
print("添加成功!")
def query_vehicle(vehicles):
print("\n--- 查询车辆 ---")
print("1. 按车牌号精确查询")
print("2. 按车主姓名查询")
print("3. 按品牌查询")
print("4. 按颜色查询")
choice = input("选择查询方式 [1-4]: ").strip()
keyword = input("请输入关键字: ").strip().lower()
results = []
for v in vehicles:
if choice == '1' and v['plate'] == keyword:
results.append(v)
elif choice == '2' and keyword in v['owner'].lower():
results.append(v)
elif choice == '3' and keyword in v['brand'].lower():
results.append(v)
elif choice == '4' and keyword in v['color'].lower():
results.append(v)
if results:
print(f"找到 {len(results)} 条记录:")
for i, v in enumerate(results, 1):
print(f"{i}. [车牌] {v['plate']} | [品牌] {v['brand']} | [车型] {v['model']} | [颜色] {v['color']} | [车主] {v['owner']} | [电话] {v['phone']} | [年份] {v['year']}")
else:
print("未找到匹配记录。")
def modify_vehicle(vehicles):
print("\n--- 修改车辆信息 ---")
plate = input("请输入要修改的车牌号: ").strip()
for i, v in enumerate(vehicles):
if v['plate'] == plate:
print(f"当前信息:{v}")
v['brand'] = input(f"新品牌 [{v['brand']}]: ") or v['brand']
v['model'] = input(f"新车型 [{v['model']}]: ") or v['model']
v['color'] = input(f"新颜色 [{v['color']}]: ") or v['color']
v['owner'] = input(f"新车主 [{v['owner']}]: ") or v['owner']
v['phone'] = input(f"新电话 [{v['phone']}]: ") or v['phone']
v['year'] = input(f"新年份 [{v['year']}]: ") or v['year']
v['updated_at'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
save_data(vehicles)
print("修改成功!")
return
print("未找到此车牌号。")
def delete_vehicle(vehicles):
print("\n--- 删除车辆 ---")
plate = input("请输入要删除的车牌号: ").strip()
for i, v in enumerate(vehicles):
if v['plate'] == plate:
confirm = input(f"确认删除 {plate} 的信息?(y/n): ").strip().lower()
if confirm == 'y':
del vehicles[i]
save_data(vehicles)
print("已删除。")
else:
print("取消删除。")
return
print("未找到此车牌号。")
def list_all(vehicles):
if not vehicles:
print("\n暂无车辆数据。")
return
print(f"\n车辆总数: {len(vehicles)}")
print("-"*80)
print(f"{'车牌':<10} {'品牌':<10} {'车型':<10} {'颜色':<8} {'车主':<10} {'电话':<15} {'年份':<6}")
print("-"*80)
for v in vehicles:
print(f"{v['plate']:<10} {v['brand']:<10} {v['model']:<10} {v['color']:<8} {v['owner']:<10} {v['phone']:<15} {v['year']:<6}")
print("-"*80)
def stat_vehicles(vehicles):
if not vehicles:
print("\n暂无车辆数据。")
return
total = len(vehicles)
print(f"\n车辆总数: {total}")
# 品牌统计
brands = {}
for v in vehicles:
brands[v['brand']] = brands.get(v['brand'], 0) + 1
print("\n品牌分布:")
for brand, count in sorted(brands.items(), key=lambda x: -x[1]):
print(f" {brand}: {count}辆 ({count/total*100:.1f}%)")
# 年份统计
years = [v['year'] for v in vehicles if v['year']]
if years:
print(f"年份范围: {min(years)} - {max(years)}")
def main():
vehicles = load_data()
while True:
show_menu()
choice = input("请输入您的选择 [0-6]: ").strip()
if choice == '1':
add_vehicle(vehicles)
elif choice == '2':
query_vehicle(vehicles)
elif choice == '3':
modify_vehicle(vehicles)
elif choice == '4':
delete_vehicle(vehicles)
elif choice == '5':
list_all(vehicles)
elif choice == '6':
stat_vehicles(vehicles)
elif choice == '0':
print("感谢使用,再见!")
sys.exit(0)
else:
print("无效输入,请重新选择。")
input("按回车键继续...")
if __name__ == "__main__":
main()
使用方法:
- 保存为
vehicle_manager.py。 - 运行
python3 vehicle_manager.py。
扩展建议
- 数据库版本(适用于大量数据):使用 SQLite 或 MySQL,语句变为 SQL 操作。
- Web 界面:使用 Flask/Django 构建 Web 版。
- 导入/导出:支持 CSV、Excel 导入导出。
- 搜索增强:支持多条件组合搜索(如品牌+年份)。
- **中文排序:Python 版本中可以使用
locale或pypinyin支持按拼音排序。
根据您的实际需求(数据量、运行环境、是否需要中文界面)选择合适版本,如有具体功能扩展需求,欢迎进一步提问!