1

I currently have the code

descarray=($(grep -oP "(?<=description\"\:)(.*?)(?=\}})" descfile.json))

but when I try this I get the match correctly but since it is a string with whitespace, it separates each word as element in array.

Example of string that match would be:

"*No_Request_Validation* issue exists @ some other information here""another example goes here"

but what I would get is

"*No_Request_Validation*
issue
exists
@
some
...

There are quotes at the start and at the end of each required elements and I would like to separate them with it. for example:

descarray[0]: "*No_Request_Validation* issue exists @ some other information here"
descarray[1]: "another example goes here"
1
  • with jq something like jq .[].description descfile.json might be more robust Commented Jun 26, 2019 at 17:59

1 Answer 1

3

You're running up against wordsplitting, which splits tokens on IFS, which includes newlines, tabs and spaces by default. To read the output of grep into an array split by newlines, consider mapfile:

mapfile -t descarray < <(grep -oP "(?<=description\"\:)(.*?)(?=\}})" descfile.json))

For example,

$ mapfile -t foo <<< '1 2 3
4 5 6'
$ echo "${#foo[@]}"  # we should see two members in the array
2
$ echo "${foo[1]}"  # The second member should be '4 5 6'
4 5 6

(Note the use of process substitution instead of a pipe. This is important to prevent an implicit subshell from eating your descarray variable.)

You can read more about mapfile in your local bash using help mapfile, or in the Bash reference manual.

Sign up to request clarification or add additional context in comments.

3 Comments

Do I need to create an empty array before running this command or is that not necessary?
If you need to parse json data, I'd strongly recommend to use the jq command.
@EDK It's not necessary to create an empty array first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.