Bash-仅在出现换行时转到下一个索引,而不是空格? [英] Bash - Only go next index when new line occurs, instead of white space?
问题描述
我正在使用名为jq的工具解析JSON响应. jq的输出将为我提供命令行中的全名列表.
I'm parsing a JSON response with a tool called jq. The output from jq will give me a list of full names in my command line.
我有一个变量 getNames ,其中包含JSON,例如:
I have the variable getNames which contains JSON, for example:
{
"count": 49,
"user": [{
"username": "jamesbrown",
"name": "James Brown",
"id": 1
}, {
"username": "matthewthompson",
"name": "Matthew Thompson",
"id": 2
}]
}
我通过以下命令将其传递给JQ以过滤json:
I pass this through JQ to filter the json using the following command:
echo $getNames | jq -r .user[].name
哪个给我这样的列表:
James Brown
Matthew Thompson
我想将这些条目中的每一个放入bash数组中,所以我输入以下命令:
I want to put each one of these entries into a bash array, so I enter the following commands:
declare -a myArray
myArray=( `echo $getNames | jq -r .user[].name` )
但是,当我尝试使用以下命令打印阵列时:
However, when I try to print the array using:
printf '%s\n' "${myArray[@]}"
我得到以下信息:
James
Brown
Matthew
Thompson
如何确保在新行之后而不是空格之后创建新索引?为什么要分隔名称?
How do I ensure that a new index is created after a new line and not a space? Why are the names being separated?
谢谢.
推荐答案
bash
中的一个简单脚本,用于将输出的每一行馈入数组myArray
.
A simple script in bash
to feed each line of the output into the array myArray
.
#!/bin/bash
myArray=()
while IFS= read -r line; do
[[ $line ]] || break # break if line is empty
myArray+=("$line")
done < <(jq -r .user[].name <<< "$getNames")
# To print the array
printf '%s\n' "${myArray[@]}"
这篇关于Bash-仅在出现换行时转到下一个索引,而不是空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!