![]() |
|
|
|
|
|||||||
| Forums | Portal | Register | Rules & FAQ | Contribute | Members List | Arcade | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts here. |
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Read csv into Hash array? | kinmak | Shell Programming and Scripting | 1 | 05-07-2008 07:35 AM |
| How to read from txt file and use that as an array | pinky | UNIX for Dummies Questions & Answers | 4 | 10-07-2007 09:18 PM |
| create array holding characters from sring then echo array. | rorey_breaker | Shell Programming and Scripting | 5 | 09-28-2007 05:42 AM |
| ls while read loop - internal read picking up wrong input | dkieran | Shell Programming and Scripting | 2 | 05-14-2007 12:02 PM |
| How can i read array elements dynamically in bash? | haisubbu | UNIX for Dummies Questions & Answers | 1 | 08-28-2006 11:19 PM |
|
|
LinkBack | Thread Tools | Display Modes |
|
|||
|
how to read a var value into array
Hi
I need to read a value of the variable into array so each character/digit will become an array element,for example: A=147921231432545436547568678679870 The resulting array should hold each digit as an element. Thanks a lot for any help -A |
| Forum Sponsor | ||
|
|
|
|||
|
Quote:
Here is the bash solution: Code:
$ A=147921231432545436547568678679870
$ set -- $(for i in $(seq 0 $((${#A} - 1)));do printf "%s " ${A:$i:1};done)
$ echo $*
1 4 7 9 2 1 2 3 1 4 3 2 5 4 5 4 3 6 5 4 7 5 6 8 6 7 8 6 7 9 8 7 0
Code:
set -- $(awk -v v="$A" 'BEGIN{split(v,a,"");for (i=1;i<= length(v);i++) printf "%s ",a[i]}')
Last edited by danmero; 07-24-2008 at 09:16 AM. Reason: add awk solution |
|
|||
|
I like this a little better than danmero's example, as it actually puts it in an array:
Code:
for i in $(seq 0 $((${#string}-1))); do array[$i]=${string:$i:1}; done
Code:
$ A=147921231432545436547568678679870; for i in $(seq 0 $((${#A}-1))); do array[$i]=${A:$i:1}; done
$ set | grep array
array=([0]="1" [1]="4" [2]="7" [3]="9" [4]="2" [5]="1" [6]="2" [7]="3" [8]="1" [9]="4" [10]="3" [11]="2" [12]="5" [13]="4" [14]="5" [15]="4" [16]="3" [17]="6" [18]="5" [19]="4" [20]="7" [21]="5" [22]="6" [23]="8" [24]="6" [25]="7" [26]="8" [27]="6" [28]="7" [29]="9" [30]="8" [31]="7" [32]="0" [33]="")
If that's what you're looking for, you can also create the same effect as danmero's script with sed: Code:
$ echo 147921231432545436547568678679870 | sed 's/\(.\)/\1 /g' 1 4 7 9 2 1 2 3 1 4 3 2 5 4 5 4 3 6 5 4 7 5 6 8 6 7 8 6 7 9 8 7 0 Last edited by BMDan; 07-24-2008 at 11:09 AM. Reason: Add sed solution |
| Tags |
| shell array, variable manipulation |
| Thread Tools | |
| Display Modes | |
|
|