shell简单处理mysql查询结果

来源:互联网 发布:caffe matlab可视化 编辑:程序博客网 时间:2024/05/18 02:59

首先理清要了解shell脚本的数组与字符串的一些特性:

str=("hello" "world" "!") #结果: str: 3  #普通的字符串数组echo "str: " ${#str[@]}str1=("hello world !")  #结果: str1: 1 #普通的字符串数组echo "str1: "${#str1[@]}str2=(`echo "Hello world !"`) #结果: str2: 3  #等价于 strecho "str2: " ${#str2[@]} function strDeal(){    param=("$@")    echo ${param[@]}    echo $1    echo $2    echo $3}echo "-----------first----------------"strDeal "Hello world !" echo "-----------second----------------"strDeal "Hello" "world" "!"echo "-----------third----------------"strDeal $str1    #等价于second

用mysql自带数据库world.city为例来展示处理查询结果

#!/bin/sh#filename:demo.shcityRes=""cityColNum=5function getCurValue(){    curValue=""    colIndex=$1    rowIndex=$2    idx=$[$cityColNum*$colIndex+$rowIndex-1]   #通过行列进行计算目标位置    if [ $idx -le ${#cityRes[@]} ] ;then        echo ${cityRes[$idx]}  #获取目标结果    fi}#获取city表总行数function getCityRowNum(){    echo $[${#cityRes[@]}/$cityColNum-1]}cityRes=(`mysql -uroot -p123456 world -e "select * from city"`)    #查询结果以数组来保存,等价于上面的str2curValue=`getCurValue $1 $2`    #$1为行数  $2为列数echo $curValuerowNum=`getCityRowNum`  #获取总行数echo $rowNum

调用示例

sh demo.sh 1 2

注意的事项

getCityRowNum后的记录数与实际的记录数并不一致,这是由于city表Name 或者District字段中由于多个字符串组成,如:Andorra la Vella
这样就会占用3个位置。

0 0