Substring in Bourne shell

Shell used: Bourne shell
Environment: UNIX in a Sun machine

I found myself struggling to figure out how to split a string. I kept wishing it's in Java that I can do it real quick.

Basically I have a string as follows:
"http://machine1:8080/aaa/bbb"

I need to get the value as follows to access the directory:
"/aaa/bbb"

I know that I need to eliminate "http://machine1:8080" and this value is read from a config file. So the length is not fixed and the value is not fixed.

I have been thinking of using grep or cut but I fail to get what I need.

Please advise. Thanks

Try expr

expr index <string> <substring> returns the offset of a small string in a larger string
expr substr <string> <offset> <[length]> returns a substring

Why can't you try sed?

echo "$string" | sed 's/\(.*\):[0-9]\{4\}\(.*\)/\2/'

Thanks a lot. You guys are really good.

It would be great if someone can explain:
sed 's/\(.*\):[0-9]\{4\}\(.*\)/\2/'

Thanks again

I just hit a problem with sed. Sorry, I don't quite understand the command sed.

x="http://10.222.11.112:866/a/bb/c/d"
echo $x
echo $x |sed 's/\(.*\):[0-9]\{4\}\(.*\)/\2/'

Output:
http://10.222.11.112:866/a/bb/c/d
http://10.222.11.112:866/a/bb/c/d

I expect:
http://10.222.11.112:866/a/bb/c/d
/a/bb/c/d

I have modified it .Earlier it will be expecting the port to a 4 digit number. I have changed it now to have 1-4 digits.

echo $x |sed 's/\(.*\):[0-9]\{1,4\}\(.*\)/\2/'

sed 's/\(.*\):[0-9]\{1,4\}\(.\)/\2/' - identifying pattern upto the ip address
sed 's/\(.*\):[0-9]\{1,4\}\(.
\)/\2/' - looking for a pattern of digits of size 1 to 4
sed 's/\(.*\):[0-9]\{1,4\}\(.\)/\2/' - looking for the pattern after the port number(here, directory)
sed 's/\(.*\):[0-9]\{1,4\}\(.
\)/\2/' - display the second group of pattern.ie,

how about:

#  echo $x |sed 's/.*:[0-9]*//'
/a/bb/c/d

On a Sun OS don't use /bin/sh; use bash, ksh or whatever POSIX shell is on the machine (perhaps in /usr/xpg4/bin).

var=http://machine1:8080/aaa/bbb
dir=/${var#*//*/}

cfajohnson, unfortunately the decision is not mine. I have to stick with whatever shell script that was previously developed. We have used a lot of Bourne shell.

Both of the following codes work perfectly. Thanks a million.

echo $x |sed 's/\(.*\):[0-9]\{1,4\}\(.\)/\2/'
echo $x |sed 's/.*:[0-9]
//'

Thanks to dennis for the detailed explanation. It helps a lot.

The code of "echo $x |sed 's/.*:[0-9]*//'" is good that I don't have to worry about the number of digits for port number.