Home > Software engineering >  How to get the name of the grandparent directory?
How to get the name of the grandparent directory?

Time:02-23

If I have the path one/two/three/four/here.md the name I should get is three.

If I have path a/b/filename.md the name should I get is a.

The path looks like ./topic/sub/guides.

CodePudding user response:

That's two dirs up and the base of a name.

var=a/b/filename.md
basename "$(dirname "$(dirname "$var")")"

CodePudding user response:

One option could be to use realpath and then basename:

the_dir='./topic/sub/guides'
basename -- "$(realpath -m -- "$the_dir/../..")"
  • Related