Neeraj
Neeraj

Reputation: 9165

How to get name of second last folder in linux

I have to write a shell script in linux in which i have to pull the name of the second last folder of the given path. For example:-

/var/www/html/folder1/folder2/folder3

How can i get only the name of second last folder "folder2" using a command?

Note: My shell script is placed at root (/var/www/html)

Upvotes: 1

Views: 3102

Answers (2)

phschoen
phschoen

Reputation: 2081

you can use sed to get it:

export some_path="/var/www/html/folder1/folder2/folder3"
export folder_place2=`echo $some_path  | sed -e "s/.*\/\([^/]*\)\/[^/]*/\1/"`
echo $folder_place2

Upvotes: 1

dogbane
dogbane

Reputation: 274670

Using awk:

awk -F/ '{print $(NF-1)}' <<< "/var/www/html/folder1/folder2/folder3"

Alternatively, call basename on the dirname.

basename "$(dirname /var/www/html/folder1/folder2/folder3)"

Upvotes: 2

Related Questions