用Shell脚本读取.csv文件并生成insert语句

shell脚本使用命令行参数指定待读取的.csv文件。.csv用于从电子表格中导出数据,所以你可以把数据库数据放入电子表格中,把电子表格保存成.csv格式,读取文件,然后创建INSERT语句将数据插入Mysql数据库。

脚本内容如下:

#!/bin/bash

oufile='student.sql' --输出语句文件

IFS=',' --指定分隔符

rm $oufile

while read id name phoneno
do
	cat >> ${oufile} << EOF
insert into student (id,name,phoneno)
values($id,$name,$phoneno);
EOF
done < ${1} --输入待读取文件

查看数据文件:

1,'张三',11
2,'李四',22
3,'王麻子',33

执行脚本:

./insert_mysql.sh student.csv

输出文件:

$ cat student.sql 
insert into student (id,name,phoneno)
values(1,'张三',11);
insert into student (id,name,phoneno)
values(2,'李四',22);
insert into student (id,name,phoneno)
values(3,'王麻子',33);

不清楚EOF用法的朋友可以查看这一篇文章:linux shell脚本EOF妙用

猜你喜欢

转载自blog.csdn.net/qq_36588424/article/details/108790403