Я думаю, что хорошее независимое от платформы решение состоит в том, чтобы использовать функцию разделения пути golang path / filepath. Не делает предположений о том, как выглядит разделитель пути, обрабатывает тома и т. Д. *
import (
"path/filepath"
)
func subpath(homeDir, prevDir string) string {
subFiles := ""
for {
dir, file := filepath.Split(prevDir)
if len(subFiles) > 0 {
subFiles = file + string(filepath.Separator) + subFiles
} else {
subFiles = file
}
if file == homeDir {
break
}
if len(dir) == 0 || dir == prevDir {
break
}
prevDir = dir[:len(dir) - 1]
}
return subFiles
}
Позвонить с
subpath("home", "allusers/user/home/path/to/file")
Для обработки случаев, когда «home» может появляться более одного раза, и вы хотите соответствовать первому:
func subpath(homeDir, prevDir string) (subFiles string, found bool) {
for {
dir, file := filepath.Split(prevDir)
if len(subFiles) > 0 {
subFiles = file + string(filepath.Separator) + subFiles
} else {
subFiles = file
}
if len(dir) == 0 || dir == prevDir {
return
}
prevDir = dir[:len(dir) - 1]
if file == homeDir {
found = true
// look for it lower down
lower, foundAgain := subpath(homeDir, prevDir)
if foundAgain {
subFiles = lower + string(filepath.Separator) + subFiles
}
return
}
}
}
Позвонить с
path, found = subpath("home", "allusers/user/home/path/home2/home/to/file")
if found {
fmt.Printf("%q\n", path)
} else {
fmt.Printf("not found\n")
}