脚本如下:

#!/bin/bash
mysql
-s -phello test >1.log <<EOF
desc t1;
EOF
lines
="concat_ws(',',"
count
=`cat 1.log|wc -l`
linenum
=0
while read line
do
coloumname
=`echo $line |awk '{print $1}'`
let linenum
=linenum+1
if [ $linenum -eq 1 ];then
lines
=$lines"concat_ws(':','{"'"'$coloumname'"'"',if("$coloumname" is null or $coloumname='','null',concat('"'"'"',$coloumname,'"'"'"')))"
elif [ $linenum -eq $count ];then
lines
=$lines",concat_ws(':','"'"'$coloumname'"'"',if("$coloumname" is null or $coloumname='','null}',concat('"'"'"',$coloumname,'"'"'"}'))))"
else
lines
=$lines",concat_ws(':','"'"'$coloumname'"'"',if("$coloumname" is null or $coloumname='','null',concat('"'"'"',$coloumname,'"'"'"')))"
fi
done < 1.log
echo $lines

表t1中的数据如下:

mysql> select * from t1;
+------+-------+
| id | name |
+------+-------+
| 1 | |
| 1 | NULL |
| 2 | hello |
+------+-------+
3 rows in set (0.00 sec)

脚本执行的结果如下:

concat_ws(',',concat_ws(':','{"id"',if(id is null or id='','null',concat('"',id,'"'))),concat_ws(':','"name"',if(name is null or name='','null}',concat('"',name,'"}'))))

在MySQL中执行的结果如下:

mysql> select concat_ws(',',concat_ws(':','{"id"',if(id is null or id='','null',concat('"',id,'"'))),concat_ws(':','"name"',if(name is null or name='','null}',concat('"',name,'"}')))) json_format from t1;
+---------------------------+
| json_format |
+---------------------------+
| {"id":"1","name":null} |
| {"id":"1","name":null} |
| {"id":"2","name":"hello"} |
+---------------------------+
3 rows in set (0.00 sec)

技巧:关于shell脚本中单引号和双引号的区别

shell脚本中的单引号和双引号一样都是字符串的界定符,而不是字符的界定符。

单引号用于保持引号内所有字符的字面值,即使引号内的\和回车也不例外,但是字符串中不能出现单引号。(注意是所有,只是单引号本身不能够出现在其中)。

双引号用于保持引号内所有字符的字面值(回车也不例外),但以下情况除外:

  • $加变量名可以取变量的值

  • 反引号仍表示命令替换

  • \$表示$的字面值

  • \`表示`的字面值

  • \"表示"的字面值

  • \\表示\的字面值

  • 除以上情况之外,在其它字符前面的\无特殊含义,只表示字面值。

更多相关文章

  1. Mysql查询时,对于数值型字段加单引号会引起的误解~
  2. 求助:json + java 返回 数据 数组中去掉双引号

随机推荐

  1. 程序员还看带广告的小说?
  2. 使用PHP反射机制获取函数文档
  3. PHP快速搭建一个简单的QQ机器人
  4. PHP实现驼峰命名和下划线命名互转
  5. PHP之你不得不知道的COOKIE含义及使用方
  6. PHP百钱百鸡问题(三种解题思路及答案)
  7. 如何用PHP代码生成金字塔
  8. PHP路由库FastRoute的使用教程
  9. PHP日期时间快速入门(图文详解)
  10. PHP简单实现路由Route功能