LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash Script (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-836400/)

mkono 10-05-2010 04:37 PM

Bash Script
 
Creating a bash script where im reading the following line from a text file: "192.168.1.1:1092" I want it to read that and have it split into two variables: IP and Port, using the ":" as a separator.

It would be nice to not have two awk statements, sed or cut.
Any help would be greatly appreciated.

unSpawn 10-05-2010 04:51 PM

You're invited to post any (pseudo) code you've got together with any errors to receive possibly constructive comments.

grail 10-05-2010 06:45 PM

I am with unSpawn, you show us what you have and where you are getting stuck (even if that is your 2 awk / other commands) and we will help you further.

janhe 10-05-2010 06:54 PM

Code:

j=0
for i in $(echo "192.168.0.1:25" | tr ":" " ")
do
  out[$j]=$i
  j=$j+1
done

Now ${out[0]} contains the IP, and ${out[1]} contains the port.

Another way to go about it is:
Code:

ip=$(echo "192.168.0.1:25" | cut -d: -f1)
port=$(echo "192.168.0.1:25" | cut -d: -f2)

These are the only solutions I can come up with. I know you don't want the second, but it is IMO the best bash can do for you. If it can be done with less code, I am open to learn.

P.S. I thought your post was very clear and you showed your work by mentioning awk, sed and cut.

catkin 10-05-2010 08:59 PM

buf=192.168.0.1:25
IP=${buf%%:*}
port=${buf##*:}

carltm 10-05-2010 09:24 PM

This can be done without the use of sed, awk or cut.
Just read up on Internal Field Separators.

mkono 10-06-2010 09:42 AM

Thanks to everyone that posted helpful solutions. It is greatly appreciated!

mkono 10-06-2010 09:47 AM

Thanks janhe. Much appreciated for the excellent help.

Quote:

Originally Posted by janhe (Post 4118833)
Code:

j=0
for i in $(echo "192.168.0.1:25" | tr ":" " ")
do
  out[$j]=$i
  j=$j+1
done

Now ${out[0]} contains the IP, and ${out[1]} contains the port.

Another way to go about it is:
Code:

ip=$(echo "192.168.0.1:25" | cut -d: -f1)
port=$(echo "192.168.0.1:25" | cut -d: -f2)

These are the only solutions I can come up with. I know you don't want the second, but it is IMO the best bash can do for you. If it can be done with less code, I am open to learn.

P.S. I thought your post was very clear and you showed your work by mentioning awk, sed and cut.


mkono 10-06-2010 09:51 AM

Thanks Catkin. I'm going to give this one a try also. Thanks!

Quote:

Originally Posted by catkin (Post 4118915)
buf=192.168.0.1:25
IP=${buf%%:*}
port=${buf##*:}


ghostdog74 10-06-2010 10:21 AM

Code:

# buf=192.168.0.1:25
# IFS=":"
# set -- $buf
# echo $1
192.168.0.1
# echo $2
25



All times are GMT -5. The time now is 07:26 AM.