Martin G
Martin G

Reputation: 18109

How to strip sub-directories from path using shell

In a make file i want to strip some sub-directories from a path given in a variable. I figure i can use $(shell ...) to do it, so a sed one-liner or similar would do the trick i think. Any suitable make technique would do though.

The path contained in the variable typically looks like:

/repo/myrepo/products/foo/prod1/test/gtest/bin/XXX

or

/repo/myrepo/products/cool_products/bar/prod2/test/gtest/bin

And i want to strip everything after prod1 and prod2 above, giving the results:

/repo/myrepo/products/foo/prod1
/repo/myrepo/products/cool_products/bar/prod2

In other words, strip all directories starting with test/gtest which i can assume is in all the paths i will be applying this to. I have not been able to figure out a clean way to strip a different number of sub-directories.

Upvotes: 0

Views: 189

Answers (2)

MadScientist
MadScientist

Reputation: 100956

Another possibility, if you want to do it with functions internal to GNU make instead of invoking a separate program via $(shell ...), would be something like:

FULL_PATH = /repo/myrepo/products/foo/prod1/test/gtest/bin/XXX

STRIPPED_PATH := $(firstword $(subst /test/gtest, ,$(FULL_PATH)))

Basically this says "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".

Upvotes: 1

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

sed 's#/test/gtest.*##g'

This will remove everything from /test/gtest to the end.

Sample:

AMD$ echo "/repo/myrepo/products/foo/prod1/test/gtest/bin/XXX" | sed 's#/test/gtest.*##g'
/repo/myrepo/products/foo/prod1

Upvotes: 2

Related Questions