[英]Parsing mysql output into bash variables is broken by white spaces
I want to read all rows in a table and put them in individual variables in bash, but I'm having a problem when the cell entries have white spaces in them:我想读取表中的所有行并将它们放在 bash 中的各个变量中,但是当单元格条目中有空格时我遇到了问题:
while read id name neighbourhood city
do
echo "ID: $id"
echo "name: $name"
echo "neighbourhood: $neighbourhood"
echo "city: $city"
echo -e "\n"
done < <(echo "SELECT id, name, neighbourhood_id, city_id FROM households" | mysql -u kong -pHarald city_planner -h 0)
If the name
is just a single word it all looks fine, but if it has three individual words separated by white space, it ends up as shown below:如果
name
只是一个单词,一切看起来都不错,但如果它包含三个由空格分隔的单词,则结果如下所示:
...
ID: 200
name: Durek
neighbourhood: 1
city: 2
ID: 201
name: Kong
neighbourhood: Harald
city: Rex 1 2
...
How can I make the whole name end up in the name variable?如何使整个名称最终出现在 name 变量中?
if you only have one string with whitespaces you can put them at the last position如果你只有一个带空格的字符串,你可以把它们放在最后一个位置
root@localhost:~# while read id neighbourhood city name
> do
> echo "ID: $id"
> echo "name: $name"
> echo "neighbourhood: $neighbourhood"
> echo "city: $city"
> echo -e "\n"
> done < <(echo "SELECT id, neighbourhood_id, city_id, name FROM households" | mysql -u root Bernd -N)
ID: 200
name: Durek
neighbourhood: 1
city: 2
ID: 201
name: Kong Harald Rex
neighbourhood: 1
city: 2
root@localhost:~#
I suggest to use "CONCAT" first and then "IFS" for while loop, like this:我建议先使用“CONCAT”,然后使用“IFS”进行 while 循环,如下所示:
while IFS='@' read -r id name neighbourhood city
do
echo "ID: $id"
echo "name: $name"
echo "neighbourhood: $neighbourhood"
echo "city: $city"
echo -e "\n"
done < <( mysql -u kong -pHarald city_planner -h 0 -NBe "SELECT CONCAT(id, '@', name, '@', neighbourhood_id, '@', city_id ) FROM households")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.