dsf
dsf

Reputation: 1215

How to get the name of the grandparent directory?

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.

EDIT:

To clear my intention, I want the "three" for example in a variable inside a bash script.

Upvotes: -1

Views: 354

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117308

One option could be to use realpath and then basename:

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

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141155

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

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

Upvotes: 1

Related Questions