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!
aigles
November 3, 2006, 12:06pm
2
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
aigles
November 3, 2006, 12:24pm
4
Try with nawk instead of awk.
Jean-Pierre.
even this doesnot work...i had previously written similarly..it doesnot work...
vino
November 4, 2006, 12:27am
6
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
aigles
November 4, 2006, 5:48am
8
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.