带有空格的Bash多行输出,作为数组变量 [英] Bash multi-line output with spaces, as array variable
问题描述
我在Mac OS X的Bash 3.2上难以处理命令输出.我有一个输出多行字符串的命令.字符串的每一行在值中都有空格.
I'm struggling with command output on Bash 3.2 on Mac OS X. I have a command that outputs a multi-line string. Each line of the string has spaces in the value.
我想将每个值分配给数组变量的元素.
I want to assign each value to an element of an array variable.
我有以下脚本:
declare -a sublist;
sublist=`azure account list --json | jsawk 'return this.name' -a 'return this.join("\n")'`;
echo ${sublist[0]};
azure
命令的输出为:
Visual Studio Ultimate with MSDN
Microsoft Partner Network
echo
命令的值是:
Visual Studio Ultimate with MSDN Microsoft Partner Network
我正在期望 echo命令的输出是:
What I'm expecting the output of the echo command to be is:
Visual Studio Ultimate with MSDN
名为 sublist
的变量应该是一个包含两个元素的数组:
The variable named sublist
should be an array, with two elements:
[0] Visual Studio Ultimate with MSDN
[1] Microsoft Partner Network
我真正挣扎的部分是将每一行,包括空格,都视为一个字符串.我已经尝试了第2行的许多变体,其中我将命令输出分配给了 sublist
变量,但没有找到一个可行的方法.
The part I'm really struggling with is getting each whole line, including its spaces, to be treated as a single string. I've tried many variations of line #2, where I assign the command output to the sublist
variable, and haven't found one that works.
推荐答案
您正在声明 sublist
为数组,但您仅分配给第一个元素( sublist
和 sublist [0]
在大多数情况下是同义词.在 bash
4中,可以使用 readarray
命令:
You are declaring sublist
to be an array, but you are only assigning to the first element (sublist
and sublist[0]
are, for the most part, synonymous). In bash
4, you can use the readarray
command:
readarray -t sublist < <(azure account list --json | jsawk 'return this.name' -a 'return this.join("\n")')
在 bash
4之前,您需要一个循环来一次为每个元素分配一个:
Prior to bash
4, you would need a loop to assign each element one at a time:
while IFS= read -r line; do
sublist+=( "$line" )
done < <(azure ...)
这篇关于带有空格的Bash多行输出,作为数组变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!