finding the last substring...

hii,
i want to know the shell command for finding the last occurance of a substring in string..
i can use grep command or sed to find out the occurance of a substring in a string but how do i find out the last occurance.shud i use grep amd and cut the string everytime and store it in a new variable until i get null for the grep..?

Thanks!

One way :

STRING="aaa;bbb;ccc"
SUBSTRING=';'
last_position=$(echo "$STRING" | awk -v str=$SUBSTRING '
   {
      while (match(substr($0, pos+1), str)) pos += RSTART;
      print pos;
      exit;
   } ')

Jean-Pierre.

This code doesnot work...itz giving me the following error..
STRING="aaa;bbb;ccc"
SUBSTRING=';'
last_position=$(echo "$STRING" | awk -v str=$SUBSTRING '
{
while (match(substr($0, pos+1), str)) pos += RSTART;
print pos;
exit;
} ')

Errors:
awk: syntax error near line 1
awk: bailing out near line 1

Try with nawk instead of awk.

Jean-Pierre.

even this doesnot work...i had previously written similarly..it doesnot work...

Does thie help ?

STRING="aaa;bbb;ccc"
SUBSTRING=';'
echo ${STRING##*$SUBSTRING}

This is what you are looking for

use this command

awk '{print $NF}' file_name

Thanks
srikanth

Add quotes " around $SUBSTRING.
If the problem persists, execute your script with the -x option and show us the trace.

STRING="aaa;bbb;ccc"
SUBSTRING=';'
last_position=$(echo "$STRING" | awk -v str="$SUBSTRING" '
   {
      while (match(substr($0, pos+1), str)) pos += RSTART;
      print pos;
      exit;
   } ')

Jean-Pierre.