Solved How to find character position in string using unix.

February 8, 2013 at 03:04:46
Specs: Windows 7

Example:
I have a string abc_def_ghg_hij, i need to get each substring upto character "_" in variables.
Like var1=abc
var2=def
var3=ghg
Can anyone help me with this?

See More: How to find character position in string using unix.

Report •


#1
February 8, 2013 at 12:33:21
✔ Best Answer

One way is to use the set command to parse the string where each segment is set to one of the command line variables and the total number of variables is $#

Warning: I haven't tested it, but you might have a problem if you have 10 or greater variables.

Let me know if you have any questions:

#!/bin/ksh

str="abc_def_ghg_hij"
set $(IFS="_"; echo $str)
###echo $# # number of variables should be 4
nv=$#

# create var1 to var4
i=1
while (($i <= $nv))
do
   eval var$i=\$$i
   ((i+=1))
done
#echo $var1

# display variables var1 to var4
h=1
while (($h <= $nv))
do
   eval echo \"\$var$h\"
   ((h+=1))
done


Report •

#2
February 8, 2013 at 22:32:48

Thanks for the reply.

But i want to assign the values to different variables. I want the output as:

name:abc
category:def
item:ghi

Can anyone help me to get the above result?


Report •

#3
February 9, 2013 at 14:01:41

Once the set command is executed:

str="abc_def_ghg_hij"
set $(IFS="_"; echo $str)

why don you just do this:

name=$1
category=$2
item=$3


Report •

Related Solutions

#4
February 9, 2013 at 21:42:35

Thanks a lot for the solution

Report •


Ask Question