我正在编写一个 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 |
+---------+------------+--------+-------------+-------+
格式化使用列-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
是的!你可以说使用从商品中选择品牌。例如,我实时使用完全不同的命令。
有任何提示或帮助吗?
答案1
mysql
与该标志一起使用-t
,可以直接从 mysql 中的查询中获取输出作为 bash 输出。
之后,您可以使用sed
或awk
来清理分隔符,以删除水平线和|
's。
答案2
mysql 的输出是制表符分隔的。column
用空格替换制表符,从而破坏您的输入。
#!/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:~#
答案3
您不必使用column
工具,因为您的桌子已经完成。尝试awk
与通用分隔符一起使用|
。
echo
您可以在您的行中执行以下操作
echo "$output" | awk -F'|' '{print $5}'
所以它结束为
#!/bin/bash
while read -r output;
do
echo $output | awk '{print $5}'
#do something
done< <(mysql -u root -ptoor super_market -h 0 -e "select * from items;" | sed '1,2d')
答案4
mysql -N -B moodle -e "select id from mdl_course;"
输出
abcd@pqrs:~/backup/script $ mysql -N -B moodle -e "select id from mdl_course;"
1
2
4
5
8
9
10
11
12
14
16
17
3
6
7
15