问题描述
我目前有验证码
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.
匹配的字符串示例为:
"*No_Request_Validation* issue exists @ some other information here""another example goes here"
但是我会得到的是
"*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"
推荐答案
您遇到了单词拆分的问题,该单词拆分IFS
上的标记,默认情况下包括换行符,制表符和空格.要将grep的输出读取到由换行符分隔的数组中,请考虑mapfile
:
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))
例如,
$ 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
(请注意,使用流程替代代替管道.这对于防止隐式操作很重要.从您的descarray
变量中删除子外壳.)
(Note the use of process substitution instead of a pipe. This is important to prevent an implicit subshell from eating your descarray
variable.)
您可以使用help mapfile
或 Bash参考手册.
这篇关于如何将grep字符串输出到bash中的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!