computing
  • 0

Solved How To Find Character Position In String Using Unix.

  • 0

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?

Share

1 Answer

  1. 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
    

    • 0