Awk结合Shell 往MySQL表中写数据吧!


需求:

1、每天根据日期在test库中创建chinacache_0726(即:chinacache_日期);

2、根据表结构处理日志文件13039_20100722_w3c,并把结果插入到创建的表中; 

awk的功能不只是简单的处理一些数据而已,看了下面的代码,结合shell,你将看到不一样的awk

代码:

!/usr/bin/awk -f

#sh.awk

BEGIN{
        "date +%m%d" | getline today
        cdn="chinacache"
        system("/usr/local/mysql/bin/mysql -uroot -proot test -e \"create table chinacache_`date +%m%d` (id int(20) NOT NULL AUTO_INCREMENT,code int(20),ip varchar(20),times int(20),cdn_name varchar(20),file varchar(256),url varchar(256),access_time varchar(30),PRIMARY KEY (id))\"")
}
{
        split($4,a,":")
        b[$1" "$7" "$9" "$11" ",a[2]":"a[3]]++
}

END{
        for(i in b){
                split(i,c," ")
                printf("insert into `%s` (code,ip,times,cdn_name,file,url,access_time) values ('%s','%s','%s','%s','%s','%s','%s');\n",cdn"_"today,c[3],c[1],b[i],cdn,c[2],c[4],c[5]);
        }

写好需求写好了代码,下面,可以结合shell把数据插入到数据库的表中:

./sh.awk /data/log/13039_20100722_w3c |/usr/local/mysql/bin/mysql -uroot -proot test

相关内容