Reputation: 35
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"
Upvotes: 1
Views: 249
Reputation: 77099
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.
Upvotes: 3