in shell script

February 26, 2009 at 03:40:55
Specs: Unix
I m using shell script .i want to select one character in a string.and also i want to find the position of that character.

See More: in shell script

Report •


#1
February 26, 2009 at 07:41:18
#!/bin/ksh

#First, find character at position 9 in a string using cut
mystring="mystringXisthis"
char9=$(echo "$mystring" | cut -c9)
echo $char9

# Second, find position of character X in the string 
length=${#mystring}

count=0
echo "$mystring" | while read str
do
   until [ $count -eq $length ]
   do
      ((count+=1))
      char=$(echo $str|cut -c"$count")
      if [[ $char == 'X' ]]
      then
         echo "character X is at position  $count"
         break
      fi
   done
done


Report •

#2
February 26, 2009 at 23:56:03
Hi nails thank u 4 ur idea but

this syntax is not working

char9=$(echo "$mystring" | cut -c9)

but this one s working

char9=`echo $mystring | cut -c9`
thank nails


Report •

#3
February 27, 2009 at 02:09:14
hi nails ,

thank u but n my sistem ur code s not working.
finally,

mystring="mystringXisthis"
char9=`echo $mystring | cut -c9`
echo $char9
length=`echo $mystring | wc -c`
length=`expr $length - 1`
echo $length
count=0
while [ $count -le $length ]
do
count=`expr $count + 1`
char=`echo $mystring | cut -c $count`
if [ $char = 'X' ]
then
echo "character X is at position $count"
break
fi
done

thsis s working ...............


Report •

Related Solutions

#4
February 27, 2009 at 07:06:14
First, I don't want to be mean, but are you aware that within the Unix/Linux world, there are multiple shells? Evidently you are using the bourne shell. The code I submitted was korn shell, ksh. There is also the bash shell - run mostly on Linux - and the "C" shell, csh & tcsh, among others.

Second, in a shell script, it's a good idea to always place the shell invocation on the first line in the first column. In your case, it's evidently:

#!/bin/sh

Third, when asking a unix question in a forum, if you state what shell you are using and what unix version (AIX, Solaris, etc), you can save yourself a lot of time.

Thank you


Report •


Ask Question