问题
I need to split a string into an array. My problem is that the delimiter is a 3 character one: _-_
For example:
db2-111_-_oracle12cR1RAC_-_mariadb101
I'd need to create the following array:
db2-111
oracle12cR1RAC
mariadb101
Similar questions followed this approach:
str="db2-111_-_oracle12cR1RAC_-_mariadb101"
arr=(${str//_-_/ })
echo ${arr[@]}
Even if the array is created, it has been split uncorrectly:
db2
111
oracle12cR1RAC
mariadb101
It seems that the "-" character in the first item causes the array's split function to fail. Can you suggest a fix for it? Thanks
回答1:
If you can, replace the _-_
sequences with another single character that you can use for field splitting. For example,
$ str="db2-111_-_oracle12cR1RAC_-_mariadb101"
$ str2=${str//_-_/#}
$ IFS="#" read -ra arr <<< "$str2"
$ printf '%s\n' "${arr[@]}"
db2-111
oracle12cR1RAC
mariadb101
回答2:
You could use sed
to do what you want, i.e. writting something like that :
str="db2-111_-_oracle12cR1RAC_-_mariadb101"
arr=($(sed 's/_-_/ /g' <<< $str))
echo ${arr[0]}
Edit :
The reason arr=(${str//_-_/ })
didn't work is that when you write it like that, everything inside ${ ... }
is considered as 1 element of the array. So, using sed
, or even simply arr=($(echo ${str//_-_/ }))
will produce the result you expect.
回答3:
Using Perl one-liner
$ echo "db2-111_-_oracle12cR1RAC_-_mariadb101" | perl -F/_-_/ -ne ' { print "$F[0]\n$F[1]\n$F[2]" } '
db2-111
oracle12cR1RAC
mariadb101
来源:https://stackoverflow.com/questions/52743297/split-string-into-array-using-multi-character-delimiter