Bash string splitting into array
I am using gnu bash 3.2
I need to split the string into array like a=this_is_whole_world.file # split [_.] I need to split this on _ and . some thing like this a[0]=this a[1]=is a[2]=whole a[3]=world a[4]=file preferable using bash regex. if not sed is also ok. Thanks Pen |
|
Code:
IFS="_" |
String splitting
thanks ghost,
But i still did't get it, can you more details, and also i need split on both underscore_ and dot. like one_two_three.four one two three four thanks Pen |
Thanks ghost
i got it, here is my final script, a="one_two_three_four.five" IFS="_." set -- $a array=( $@ ) echo ${#array[@]} # length of array echo ${array[0]} # echo ${array[1]} echo ${array[2]} echo ${array[3]} echo ${array[4]} #five |
i'd prefer to use read for that:
Code:
IFS=... Code:
[[ BASH_VERSINFO -ge 3 ]] |
How about
Code:
IFS='_.' When IFS is unset, bash behaves as if it had the default value so unsetting it is a neater solution than saving it and restoring it unless it may be set to a non-default value. EDIT: tested on bash version 3.1.17 |
Well if it comes down to playing with IFS I would go for:
Code:
IFS='_.' read -r -a ARR <<< "$string" |
Thanks Grail, your solution looks idle,
Thanks catkin and Konsolebox giving soulution. Pen |
No probs ... always more than one way to skin a cat so I am learning everyday :)
Please mark as SOLVED if you have your solution. |
Quote:
|
Nice one grail. :)
Now I no longer have to use a wrapper function. Or maybe now just optional. |
Code:
User@term$ func() { i=0; while [[ $i != ${#1} ]]; do ARR[$i]="${1:$i:$((${#1}-$((${#1}-1))))}"; echo ${ARR[$i]}; let i=$i+1; done } : ) |
@Gussy - I am not sure what you mean? You created a function and then ran it with a string ... how is that helpful to this thread?
Also is there a reason for the convoluted length expression? Code:
ARR[$i]="${1:$i:$((${#1}-$((${#1}-1))))}" |
Quote:
I'm very used to seeing people having problems with breaking up strings into characters. |
All times are GMT -5. The time now is 07:15 PM. |