我正在尝试使用数组从多个元素的变量中打印一个单词。这是一个脚本:
location=($(here mysql query to extract name of locations))
for i in "${location[@]}"; do
echo "$i"
done
但是这些位置名称包含空格:MUMBAI - BORIVALI
,DELHI - LAJPATNAGAR
等等。因此它打印如下:调试模式下的输出:
+ for i in '"${LOCATION[@]}"'
+ echo DELHI
DELHI
+ for i in '"${LOCATION[@]}"'
+ echo -
-
+ for i in '"${LOCATION[@]}"'
+ echo LAJPATNAGAR
LAJPATNAGAR
+ for i in '"${LOCATION[@]}"'
+ echo MUMBAI
MUMBAI
+ for i in '"${LOCATION[@]}"'
+ echo -
-
+ for i in '"${LOCATION[@]}"'
+ echo BORIVLI
BORIVLI
我尝试过双引号:
location=("$(here mysql query to extract name of locations)")
然后输出
+ for i in '"${LOCATION[@]}"'
+ echo 'DELHI - LAJPATNAGAR
MUMBAI - BORIVLI'
在一起。
我想要输出:
+ echo 'DELHI - LAJPATNAGAR'
DELHI - LAJPATNAGAR
+ echo 'MUMBAI - BORIVLI'
MUMBAI - BORIVLI
答案 0 :(得分:1)
如果地点不包含换行符,您可以尝试
while read -r location ; do
echo "$location"
done < <(mysql ...)
如果只给出一个参数, read
会逐行读取。默认情况下,它从stdin读取,但是通过进程替换,我们将mysql
命令的输出重定向到它。
答案 1 :(得分:0)
尝试将IFS设置为仅限换行符:
IFS="$(echo)"
location=($(here mysql query to extract name of locations))
for i in "${location[@]}"; do
echo "$i"
done
test.txt
的示例:
A B C
D E
F
运行上面的代码,用cat test.txt
替换MySQL查询。输出:
A B C
D E
F
如果您放弃IFS="$(echo)"
行,则会在单独的一行中显示每个字母。
答案 2 :(得分:0)
只计算3个字段:
location=($(here mysql query to extract name of locations))
for ((i=0; i <= ${#location}; i+=3))
do
echo "${location[i]} ${location[i+1]} ${location[i+2]}"
done