微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Bash脚本中的Mysql输出格式

我正在写一个bash脚本,我在那个脚本中使用mysql查询,我得到的格式是完全不同的.

查询

root@debian:~# MysqL -u root -ptoor super_market -h 0 -e "select * from items;" 
+---------+------------+--------+-------------+-------+
| item_id | item_name  | weight | brand       | price |
+---------+------------+--------+-------------+-------+
|       1 | Milk       |   2.00 | nestle      |  2.00 |
|       2 | Cheese     |   2.50 | Amul        |  6.00 |
|       3 | Chips      |  25.00 | Lays        |  3.00 |
|       4 | Coke       |   5.00 | Coke Cola   |  3.50 |
|       5 | Engage     |   5.00 | Deo         |  3.50 |
|       6 | Engage     |   5.00 | Deo         |  3.50 |
|       7 | Ear phones |   4.00 | Skull Candy | 32.30 |
+---------+------------+--------+-------------+-------+

使用column -t命令格式化输出格式

root@debian:~# MysqL -u root -ptoor super_market -h 0 -e "select * from items;" | column -t
item_id  item_name  weight  brand   price
1        Milk       2.00    nestle  2.00
2        Cheese     2.50    Amul    6.00
3        Chips      25.00   Lays    3.00
4        Coke       5.00    Coke    Cola   3.50
5        Engage     5.00    Deo     3.50
6        Engage     5.00    Deo     3.50
7        Ear        phones  4.00    Skull  Candy  32.30

Bash脚本
我尝试使用上面的命令的bash脚本

root@debian:~# cat test
#!/bin/bash

while read -r output;
do
    echo $output | awk '{print $4}'
    #do something
done< <(MysqL -u root -ptoor super_market -h 0 -e "select * from items;" | sed 1d |column -t)

产量

root@debian:~# ./test
nestle
Amul
Lays
Coke
Deo
Deo
4.00

但预期产出:

nestle
Amul
Lays
Coke Cola
Deo
Deo
Skull Candy

是啊!你可以说从商品中选择品牌.这是例如实时我使用完全不同的命令.

任何提示或帮助?

解决方法:

MysqL输出是制表符分隔的.列用空格替换选项卡以破坏输入.

#!/bin/bash

while read -r output;
do
    # use double quotes with "$output" to avoid conversion
    # of tabs to spaces and set awk's Field Separator to "\t"
    echo "$output" | awk -F"\t" '{print $4}'
    #do something
done< <(MysqL -u root -ptoor super_market -h 0 -e "select * from items;" | sed 1d)

测试运行:

root@c2:~# MysqL -u root -ptoor super_market -h 0 -e "select * from items;"
+---------+------------+--------+-------------+-------+
| item_id | item_name  | weight | brand       | price |
+---------+------------+--------+-------------+-------+
|       1 | Milk       |      2 | nestle      |     2 |
|       2 | Cheese     |    2.5 | Amul        |     6 |
|       3 | Chips      |     25 | Lays        |     3 |
|       4 | Coke       |      5 | Coke Cola   |   3.5 |
|       5 | Engage     |      5 | Deo         |   3.5 |
|       6 | Engage     |      5 | Deo         |   3.5 |
|       7 | Ear phones |      4 | Skull Candy |  32.3 |
+---------+------------+--------+-------------+-------+
root@c2:~# ./test.sh 
nestle
Amul
Lays
Coke Cola
Deo
Deo
Skull Candy
root@c2:~# 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐