With bash and a regex:
s="/dir0/dir1/dir2/filename.ext"
[[ $s =~ ([^/]*)/[^/]*$ ]] && echo "${BASH_REMATCH[1]}"
Output:
dir2
With bash and a regex:
s="/dir0/dir1/dir2/filename.ext"
[[ $s =~ ([^/]*)/[^/]*$ ]] && echo "${BASH_REMATCH[1]}"
Output:
dir2