I seem to have failed at something pretty simple, in bash. I have a string variable that holds the full path to a directory. I\'d like to assign the last two di
I don't know of a method specifically for trimming paths, but you can certainly do it with bash's regular expression matching:
DIRNAME=/a/b/c/d/e
if [[ "$DIRNAME" =~ ([^/]+/+[^/]+)/*$ ]]; then
echo "Last two: ${BASH_REMATCH[1]}"
else
echo "No match"
fi
Note: I've made the pattern here a little more complex than you might expect, in order to handle some allowed-but-not-common things in the path: it trims trailing slashes, and tolerates multiple (redundant) slashes between the last two names. For example, running it on "/a/b/c//d//" will match "c//d".