Chinaunix首页 | 论坛 | 博客
  • 博客访问: 198186
  • 博文数量: 42
  • 博客积分: 2520
  • 博客等级: 少校
  • 技术积分: 392
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-26 16:41
文章分类

全部博文(42)

文章存档

2010年(4)

2009年(38)

我的朋友

分类: Mysql/postgreSQL

2009-05-13 09:18:09

Using command line tools to export data from a MySQL database into a CSV file is quite easy. Here's how:

mysql -uexampleuser -pletmein exampledb -B -e "select * from \`person\`;" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > filename.csv

Here is some sample output of the above:

"id","username","group","password"
"1","tux","admin","5f4dcc3b5aa765d61d8327deb882cf99"
"2","tlugian","admin","5f4dcc3b5aa765d61d8327deb882cf99"
"3","saiyuki","admin","5f4dcc3b5aa765d61d8327deb882cf99"
"4","fred","staff","5f4dcc3b5aa765d61d8327deb882cf99"
"5","barney","staff","5f4dcc3b5aa765d61d8327deb882cf99"
"6","wilma","admin","5f4dcc3b5aa765d61d8327deb882cf99"

And now for the explanation:

Starting with the MySQL command. I wont explain the -u and -p options they are straight forward (if in doubt man mysql). The -B option will delimit the data using tabs and each row will appear on a new line. The -e option denotes the command to run once you have logged into the database. In this case we are using a simple SELECT statement.

Onto sed. The command used here contains three seperate sed scripts:

s/\t/","/g;s/^/"/        <--- this will search and replace all occurences of 'tabs' and replace them with a ",".

;s/$/"/;    <--- This will place a " at the start of the line.

s/\n//g    <---- This will place a " at the end of the line.

After running the result set through sed we redirect the output to a file with a .csv extension.

阅读(1119) | 评论(0) | 转发(0) |
0

上一篇:为Python添加默认模块搜索路径

下一篇:sed

给主人留下些什么吧!~~