Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I want to split "12345678" into
first variable or arr[0]=12
second variable or arr[1]=34
third variable or arr[2]=56
fourth variable or arr[3]=78

How can I do this in UNIX shell scripting without any delimiter of ;,,: etc...
Posted
Updated 16-Dec-15 1:42am
v2

1 solution

You can use the Substring Extraction (see http://tldp.org/LDP/abs/html/string-manipulation.html[^]):
stringInput=12345678
str1=${stringInput:0:2} # 12
str2=${stringInput:2:2} # 34
str3=${stringInput:4:2} # 56
str4=${stringInput:6:2} # 78

If the input string has variable length use a loop (${#stringInput} returns the length of the string and use variables for the position and length parameters of the substring extraction).

[EDIT]
The above are for bash. But the link contains also examples using the UNIX expr command. But note that the expr command uses 1-based indexes.
 
Share this answer
 
v2
Comments
Leo Chapiro 16-Dec-15 7:00am    
Nice solution, +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900