如何使用 shell 从路径中删除子目录
How to strip sub-directories from path using shell
在生成文件中,我想从变量中给定的路径中删除一些子目录。我想我可以使用 $(shell ...)
来做到这一点,所以我认为 sed
单线或类似的东西可以达到目的。任何合适的 make
技术都可以。
变量中包含的路径通常如下所示:
/repo/myrepo/products/foo/prod1/test/gtest/bin/XXX
或
/repo/myrepo/products/cool_products/bar/prod2/test/gtest/bin
我想删除上面 prod1
和 prod2
之后的所有内容,给出结果:
/repo/myrepo/products/foo/prod1
/repo/myrepo/products/cool_products/bar/prod2
换句话说,删除所有以 test/gtest
开头的目录,我可以假设它在我将应用它的所有路径中。我一直没能想出一个干净的方法来剥离不同数量的子目录。
sed 's#/test/gtest.*##g'
这将删除从 /test/gtest
到结尾的所有内容。
示例:
AMD$ echo "/repo/myrepo/products/foo/prod1/test/gtest/bin/XXX" | sed 's#/test/gtest.*##g'
/repo/myrepo/products/foo/prod1
另一种可能性,如果您想使用 GNU make 的内部函数而不是通过 $(shell ...)
调用单独的程序,则类似于:
FULL_PATH = /repo/myrepo/products/foo/prod1/test/gtest/bin/XXX
STRIPPED_PATH := $(firstword $(subst /test/gtest, ,$(FULL_PATH)))
基本上就是说 "take $(FULL_PATH)
and first replace the string /test/gtest
with a space character everywhere it appears in the string, then return the first word of the resulting string"。
在生成文件中,我想从变量中给定的路径中删除一些子目录。我想我可以使用 $(shell ...)
来做到这一点,所以我认为 sed
单线或类似的东西可以达到目的。任何合适的 make
技术都可以。
变量中包含的路径通常如下所示:
/repo/myrepo/products/foo/prod1/test/gtest/bin/XXX
或
/repo/myrepo/products/cool_products/bar/prod2/test/gtest/bin
我想删除上面 prod1
和 prod2
之后的所有内容,给出结果:
/repo/myrepo/products/foo/prod1
/repo/myrepo/products/cool_products/bar/prod2
换句话说,删除所有以 test/gtest
开头的目录,我可以假设它在我将应用它的所有路径中。我一直没能想出一个干净的方法来剥离不同数量的子目录。
sed 's#/test/gtest.*##g'
这将删除从 /test/gtest
到结尾的所有内容。
示例:
AMD$ echo "/repo/myrepo/products/foo/prod1/test/gtest/bin/XXX" | sed 's#/test/gtest.*##g'
/repo/myrepo/products/foo/prod1
另一种可能性,如果您想使用 GNU make 的内部函数而不是通过 $(shell ...)
调用单独的程序,则类似于:
FULL_PATH = /repo/myrepo/products/foo/prod1/test/gtest/bin/XXX
STRIPPED_PATH := $(firstword $(subst /test/gtest, ,$(FULL_PATH)))
基本上就是说 "take $(FULL_PATH)
and first replace the string /test/gtest
with a space character everywhere it appears in the string, then return the first word of the resulting string"。