Bash - Only go next index when new line occurs, instead of white space?

青春壹個敷衍的年華 提交于 2020-08-19 17:58:02

问题


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.

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
    }]
}

I pass this through JQ to filter the json using the following command:

echo $getNames | jq -r .user[].name

Which gives me a list like this:

James Brown   
Matthew Thompson   

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[@]}"

I get the following:

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?

Thanks.


回答1:


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[@]}"



回答2:


Just use mapfile command to read multiple lines into an array like this:

mapfile -t myArray < <(jq -r .user[].name <<< "$getNames")


来源:https://stackoverflow.com/questions/38633599/bash-only-go-next-index-when-new-line-occurs-instead-of-white-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!