You need to look at this URL
You will find following solutions on this URL
I am not able add comment so I am Just copy paste Ans
If you wanted to remove a certain NUMBER of path components, you should use cut with -d'/'. For example, if path=/home/dude/some/deepish/dir:
To remove the first two components:
$ echo $path | cut -d'/' -f4-
some/deepish/dir
To remove the last three components (assuming no trailing slash):
$ echo $path | cut -d'/' -f-3
/home/dude
To KEEP the last three components (rev reverses the string):
$ echo $path | rev | cut -d'/' -f-3 | rev
some/deepish/dir
Or, if you want to remove everything before a particular component, sed would work:
$ echo $path | sed 's/.*(some)/\1/g'
some/deepish/dir
Or after a particular component:
$ echo $path | sed 's/(dude).*/\1/g'
/home/dude
It's even easier if you don't want to keep the component you're specifying:
$ echo $path | sed 's/some.*//g'
/home/dude/
And if you want to be consistent you can match the trailing slash too:
$ echo $path | sed 's//some.*//g'
/home/dude
Of course, if you're matching several slashes, you should switch the sed delimiter:
$ echo $path | sed 's!/some.*!!g'
/home/dude
Also, if you have filenames with / characters in them, you're totally boned.