See this link for a long list of built-in bash string manipulations. Your challenge here is to split up the string into individual directory elements, and output only the ones you want. In addition to the suggestions grail gave above, you could use an array, or
read, and perhaps a few others.
http://mywiki.wooledge.org/BashFAQ/100
Here's a quick example function I just wrote up using an array:
Code:
extractpath(){
#print an arbitrary number of levels from a given file path
#$1 is the path, $2 is the number of levels to print
local IFS='/'
local -a path=( $1 )
echo "/${path[*]:1:$2}"
}
$ extractpath "/home/david/temp/test/foo/bar/baz" 4
/home/david/temp/test
And here's an example of how to use read (and a
here string to pass the pathname to it):
Code:
$ IFS='/' read _ a b c d e _ <<<"/home/david/temp/test/foo/bar/baz"
$ echo "/$a/$b/$c/$d/$e"
/home/david/temp/test/foo
Note that you could also just use read's
-a option to load an array instead.
Also notice that when IFS is set to anything other than whitespace, then the empty string in front of the first delimiter is treated as the first entry. That's why the echoing of the array in the function starts with field 1, and the disposable "_" variable is included at the start in the read command (as well as at the end, where it catches all the trailing fields we don't want).
Finally, one more way to grab arbitrary numbers of levels, using parameter expansion:
Code:
$ fullpath='/home/david/temp/test/foo/bar/baz/'
$ keeppath="${fullpath#/*/*/*/}" #use the desired number of /*/ levels you want to keep
$ echo "${fullpath%$keeppath}"
/home/david/temp/
Be careful with this one though. The exact pattern you need to use depends on whether the fullpath has a trailing slash or not.