-1

I need to split string into array. here is my string

`Dec 10 03:39:13 cgnat2.dd.com 1 2015 Dec 9 14:39:11 01-g3-adsl - - NAT44 -

[UserbasedW - 100.70.24.236 vrf-testnet - 222.222.34.65 - 3072 4095 - - ]

[UserbasedW - 100.70.25.9 vrf-testnet - 222.222.34.65 - 16384 17407 - - ]

[UserbasedW - 100.70.25.142 vrf-testnet - 222.222.34.69 - 9216 10239 - - ]`

my output array should be

Dec 10 03:39:13 cgnat2.dd.com 1 2015 Dec 9 14:39:11 01-g3-adsl - - NAT44 - [UserbasedW - 100.70.24.236 vrf-testnet - 222.222.34.65 - 3072 4095 - - ] [UserbasedW - 100.70.25.9 vrf-testnet - 222.222.34.65 - 16384 17407 - - ] [UserbasedW - 100.70.25.142 vrf-testnet - 222.222.34.69 - 9216 10239 - - ]

how can i do this ??

chinthaka
  • 69
  • 10

2 Answers2

1

There are a number of ways to approach the separation into an array. In bash, you have command substitution and herestrings that cam make it relatively painless. You will need to control word-splitting, which you can do by setting the internal field separator to only break on newlines. To load the separated string into the array, you have several options. Presuming you have the string contained in variable named string, you can do something similar to the following.

oifs="$IFS"     ## save current Internal Field Separator
IFS=$'\n'       ## set to break on newline only

## separate string into array using sed and herestring
array=( $(sed 's/[ ][[]/\n[/g' <<<"$string") )

IFS="$oifs"     ## restore original IFS

This is not the only way to approach the matter. You can also use process substitution along with read to add each of the separated lines to the array with a ... while read -r line; do array+=("$line"); done < <(sed ...) approach.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

It's not entirely clear what you are trying to do, but the following pipeline does split your string at the boundaries defined by square brackets:

sed -e $'s/\\(\\]\\)/\\1\t/g' -e $'s/\\(\\[\\)/\t\\1/g'  | tr '\t' '\n' | grep -v '^$'

Output:

Dec 10 03:39:13 cgnat2.dd.com 1 2015 Dec 9 14:39:11 01-g3-adsl - - NAT44 -
[UserbasedW - 100.70.24.236 vrf-testnet - 222.222.34.65 - 3072 4095 - - ]
[UserbasedW - 100.70.25.9 vrf-testnet - 222.222.34.65 - 16384 17407 - - ]
[UserbasedW - 100.70.25.142 vrf-testnet - 222.222.34.69 - 9216 10239 - - ]
peak
  • 105,803
  • 17
  • 152
  • 177