[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: split a string into an array?
From: |
Kerin Millar |
Subject: |
Re: split a string into an array? |
Date: |
Fri, 11 Mar 2022 04:07:27 +0000 |
On Thu, 10 Mar 2022 21:25:53 -0600
Peng Yu <pengyu.ut@gmail.com> wrote:
> Hi,
>
> I currently use the following method to split a string into an array
> using a separator (TAB is used in the example, but it could be other
> characters). Is this a robust way to do so? Is there any corner case
> that it will not handle correctly?
>
> $ readarray -t -d $'\t' array <<< $'a\t\tb\tc'
> $ array[-1]=${array[-1]%$'\n'}
> $ declare -p array
> declare -a array=([0]="a" [1]="" [2]="b" [3]="c")
Here is a corner case:
$ readarray -t -d $'\t' array <<<''
$ array[-1]=${array[-1]%$'\n'}
$ declare -p array
declare -a array=([0]="")
You could do it this way instead:
$ readarray -t -d $'\t' array < <(printf %s $'a\t\tb\tc')
$ declare -p array
declare -a array=([0]="a" [1]="" [2]="b" [3]="c")
$ readarray -t -d $'\t' array < <(printf '')
$ declare -p array
declare -a array=()
> Also, when the separator is not a single character but rather a regex,
> is there a good way to split a string into an array? Thanks.
Only lightly tested ...
#!/bin/bash
re='[,|]'
str='foo|bar,baz|quux'
fields=()
while [[ $str =~ ($re) ]]; do
value=${str%%"${BASH_REMATCH[1]}"*}
fields+=("$value")
str=${str:${#value} + ${#BASH_REMATCH[1]}}
done
fields+=("$str")
declare -p fields
The result is as follows.
declare -a fields=([0]="foo" [1]="bar" [2]="baz" [3]="quux")
--
Kerin Millar