Results 1 to 5 of 5
Hi,
I have a string which is an IP Address, I want to spli the octets into an array and retrieve the individual octets. Here is what I have got ...
- 12-28-2009 #1Just Joined!
- Join Date
- Jun 2008
- Posts
- 33
Bash split string into array
Hi,
I have a string which is an IP Address, I want to spli the octets into an array and retrieve the individual octets. Here is what I have got so far:
I can print the entire array out with this line of code:Code:# create the string IP address IPSTR="192.168.1.4" # declare the array declare -a IPARR IP_ARR=$(echo $IPSTR | tr "." " ") # print out the first octet (should be 192). This actually prints out a blank line echo ${IPARR[0]} # also tried with quotes, but same result: echo "${IPARR[0]}"
I can also loop through the array and print out the octets one by one. But I want to be able to access them directly without having to loop.Code:echo ${IPARR[@]}
Anyone know why it prints out a blank line when I try to access an array element?
- 12-28-2009 #2Linux User
- Join Date
- Aug 2006
- Posts
- 458
Code:ip="192.168.0.1" IFS="." set -- $ip echo "$1,$2,$3,$4"
- 12-28-2009 #3Just Joined!
- Join Date
- Jun 2008
- Posts
- 33
Thanks ghostdog, I've seen that method from searching. I was hoping to be able to achieve this by using tr method.
I think it is an issue with the array keys. After the string being split into the array, it doesn't have keys of 0,1,2,3 as I would expect. It does have keys though but I can't see what they are, I know this because when I do a "for in" loop, the data is retrieved.
Perhaps it's the array declaration needing some syntax to say it's a numerical key array.
- 12-29-2009 #4Linux Newbie
- Join Date
- Sep 2005
- Location
- CZ
- Posts
- 164
Works for me...Code:# create the string IP address IPSTR="192.168.1.4" # declare the array declare -a IPARR IPARR=(`echo $IPSTR | tr "." " "`) # print out the first octet (should be 192). This actually prints out a blank line echo ${IPARR[0]} # also tried with quotes, but same result: echo "${IPARR[0]}"
You should slap yourself...

Or:
- Read carefully, IP_ARR is not the same as IPARR
- Array should be initialized with (content1 content2)
- is useful when debugging your scripts. After your debug process is done, you can remove the -x parameterCode:
#! /bin/bash -x
- 01-01-2010 #5Just Joined!
- Join Date
- Jun 2007
- Posts
- 12
Don't use a pipe as it causes a new process to be created. Here is your code with a small change. Use "IPARR=(`echo ${IPSTR//./ }`)" instead of "IPARR=(`echo $IPSTR | tr "." " "`)"
# create the string IP address
IPSTR="192.168.1.4"
# declare the array
declare -a IPARR
IPARR=(`echo ${IPSTR//./ }`)
# print out the first octet (should be 192). This actually prints out a blank line
echo ${IPARR[0]}
# also tried with quotes, but same result:
echo "${IPARR[0]}"


Reply With Quote