2

当我运行以下代码时,当数据中有空间时,存储在变量部门、testDate 和 testTime 中的数据会相互混合,例如,如果“计算机科学”是部门名称,则“计算机”存储在变量 department和“科学”存储在testDate变量中,但显然我想将整个“计算机科学”存储在变量中department以及变量的数据中
testDatetestTime因为您还可以在输出中观察到问题。我该如何解决这个问题?

mysql -uroot -proot -Dproject_ivr_db -rN --execute "SELECT Dpartment,TestDate,
TestTime FROM entrytests_datetime WHERE Discipline='msc'" |
while read department testDate testTime 
do

    echo "V,department=$department"
    echo "V,testDate=$testDate"
    echo "V,testTime=$testTime"

done

echo "E,resume"

输出:

  V,department=computer
  V,testDate=science
  V,testTime=first february 2013    nine thirty a m
  V,department=electronics
  V,testDate=first
  V,testTime=february 2013  ten thirty a m
  E,resume
4

1 回答 1

1

基本上,您必须确保输出中的字段与mysql空格以外的某个字符分开,并且您必须告诉外壳程序是哪个字符。

告诉 shell 是用 IFS 变量完成的。

使用or选项来告诉mysql命令:--batch-B

--batch,-B

使用制表符作为列分隔符打印结果,每行换行。使用此选项,mysql不使用历史文件。

批处理模式导致非表格输出格式和特殊字符转义。使用 raw 模式可以禁用转义;请参阅该--raw选项的说明。

所以:

IFS="   "   # Tab (only) in quotes
mysql -B -uroot -proot -Dproject_ivr_db -rN --execute "SELECT Dpartment,TestDate,
TestTime FROM entrytests_datetime WHERE Discipline='msc'" |
while read department testDate testTime 
do

    echo "V,department=$department"
    echo "V,testDate=$testDate"
    echo "V,testTime=$testTime"

done

echo "E,resume"
于 2013-02-21T07:13:24.473 回答