#Shell脚本 -- 由json文件生成sql
#json文件格式:
$ head accounts.json
{"index":{"_id":"1"}}
{"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}
{"index":{"_id":"6"}}
{"account_number":6,"balance":5686,"firstname":"Hattie","lastname":"Bond","age":36,"gender":"M","address":"671 Bristol Street","employer":"Netagy","email":"hattiebond@netagy.com","city":"Dante","state":"TN"}
#将偶数行内容转成insert sql
$ head accounts.json | grep -v index | awk ' {s=substr($0, 2, length($0)-3); split(s,a,","); for(k=1; k<=length(a);k++){split(a[k], b, ":"); t[b[1]]=b[2]}; columns=""; values="";for(k in t){c=k; gsub("\"","",c);columns=columns ", " c ; values=values "," t[k]} print "insert into accounts("substr(columns,2)") values("substr(values,2)");"}'
insert into accounts( gender, state, email, employer, account_number, age, lastname, firstname, city, address, balance) values("M","IL","amberduke@pyrami.com","Pyrami",1,32,"Duke","Amber","Brogan","880 Holmes Lane",39225);
insert into accounts( gender, state, email, employer, account_number, age, lastname, firstname, city, address, balance) values("M","TN","hattiebond@netagy.com","Netagy",6,36,"Bond","Hattie","Dante","671 Bristol Street",5686);
参考文档:
http://www.cnblogs.com/chengmo/archive/2010/10/08/1846190.html
https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html