我想编写一个读取csv文件并创建sql文件的脚本?所以我在file.csv文件中有几个数据,如:
Ball,Jamin,1414 Willow Rd。,Cupertino,CA,94024Church,Joe,2500 Main St.,Los …
Bash循环
while IFS=',' read -r lname fname address city state zip; do printf "INSERT INTO students (lname,fname,address,city,state,zip) VALUES\n" printf "('%s', '%s', '%s', '%s', '%s', %s');\n" "$lname" "$fname" "$address" "$city" "$state" "$zip" done <<EOF Ball,Jamin,1414 Willow Rd.,Cupertino,CA,94024 Church,Joe,2500 Main St.,Los Altos,CA,94023 Foothill,Ann,12345 El Monte Rd.,Los Altos,CA,94022 EOF
缓慢但灵活。
Awk脚本
awk -F',' '{ print "INSERT INTO students (lname,fname,address,city,state,zip) VALUES" print "('\''" $1 "'\'', '\''" $2 "'\'', '\''" $3 "'\'', '\''" $4 "'\'', '\''" $5 "'\'', '\''" $6 "'\'');" }' <<EOF Ball,Jamin,1414 Willow Rd.,Cupertino,CA,94024 Church,Joe,2500 Main St.,Los Altos,CA,94023 Foothill,Ann,12345 El Monte Rd.,Los Altos,CA,94022 EOF
使用它自己的语法更快,但外部工具。这里引用的也是痛苦,但是可以通过将脚本作为带有awk shebang的awk脚本来减少它:
cat <<'EOF' >script.awk #!/bin/awk -f BEGIN { FS="," } { print "INSERT INTO students (lname,fname,address,city,state,zip) VALUES" print "('" $1 "', '" $2 "', '" $3 "', '" $4 "', '" $5 "', '" $6 "');" } EOF chmod +x script.awk ./script.awk <<EOF Ball,Jamin,1414 Willow Rd.,Cupertino,CA,94024 Church,Joe,2500 Main St.,Los Altos,CA,94023 Foothill,Ann,12345 El Monte Rd.,Los Altos,CA,94022 EOF