You need to be careful, but you can make the shell substitution work. For example:
keep="projects"
base="${DIRNAME%/$keep/*}/$keep"
Note that the /$keep/ part ensures that you get the right path with /path/to/projects/with/remote_projects_here/to/confuse/you; your original would mismanage that string.
You can also do it with sed:
base=$(sed "s%\(.*/$keep\)/.*%\1%" <<< "$DIRNAME")
using a here string; or you could do it the portable and classic way with echo:
base=$(echo "$DIRNAME" | sed "s%\(.*/$keep\)/.*%\1%")
Of course, you can still run into problems with what's in the sub-directory names:
/path/to/projects/with/remote_projects_here/projects/select
Test code:
#!/bin/bash
My_Dir=projects
keep="projects"
for dir in \
/path/to/projects/proj1/dir1 \
/path/to/projects/with/remote_projects_here/to/confuse/you
do
DIRNAME="$dir"
echo "Data"
echo "$DIRNAME"
echo "Original"
echo "${DIRNAME%$My_Dir*}"
echo "Variant 1"
base="${DIRNAME%/$keep/*}/$keep"
echo "$base"
echo "Variant 2"
base=$(sed "s%\(.*/$keep\)/.*%\1%" <<< "$DIRNAME")
echo "$base"
echo "Variant 3"
base=$(echo "$DIRNAME" | sed "s%\(.*/$keep\)/.*%\1%")
echo "$base"
done
Example output:
Data
/path/to/projects/proj1/dir1
Original
/path/to/
Variant 1
/path/to/projects
Variant 2
/path/to/projects
Variant 3
/path/to/projects
Data
/path/to/projects/with/remote_projects_here/to/confuse/you
Original
/path/to/projects/with/remote_
Variant 1
/path/to/projects
Variant 2
/path/to/projects
Variant 3
/path/to/projects
The output could be better formatted, but it makes the point.