0

I have a issue when iterating string with lines. Check the following code:

file='[
    {"name" : "a b"},
    {
        "name" : "c"
    },
    {
        "name" : "d"
    }
]'

lines=$(jq -c '.[]' <<< "$file")
echo "lines $lines"

echo "\niterating #1:"
for i in ${lines//\\n/ }; do
  echo "item: $i"
done

echo "\niterating #2:"
while read -r line; do
  echo "item: $line"
done <<< $lines

And the result is note expected. It breaks a line into two because there is a space in a field value.

lines {"name":"a b"}
{"name":"c"}
{"name":"d"}

iterating #1:
item: {"name":"a
item: b"}           # <-- don't want break here
item: {"name":"c"}
item: {"name":"d"}

iterating #2:
item: {"name":"a b"} {"name":"c"} {"name":"d"} # <-- seems no new line?
Ron
  • 6,037
  • 4
  • 33
  • 52
  • If it's JSON format you might want to have a browse through this question and answers: https://unix.stackexchange.com/questions/121718/how-to-parse-json-with-shell-scripting-in-linux – neophytte Jan 05 '23 at 04:27
  • What is purpose of looping output of `jq` in bash? – anubhava Jan 05 '23 at 04:38
  • If you want to split the items on newlines, use `mapfile`. `mapfile -t ary <<< "$lines"; for i in "${ary[@]}"; do echo "item: $i"; done` – tshiono Jan 05 '23 at 04:45
  • Answer: `jq -c '.[]' <<< "$file" | while read i; do echo "item: $i" done`. Compared with what I did in `iterating #2`, the difference is that I put the jq result into a variable and then iterate, while the answer is using pipe. It seems that it will lost all the new lines if via a variable. – Ron Jan 05 '23 at 04:57
  • 1
    Your attempts are splitting things on whitespace where you want to only split on newlines. The lack of quoting is part of the problem. Perhaps see [When to wrap quotes around a shell variable](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Jan 05 '23 at 07:27

0 Answers0