How to get name of second last folder in linux

六月ゝ 毕业季﹏ 提交于 2019-12-24 10:47:38

问题


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)

回答1:


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)"



回答2:


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


来源:https://stackoverflow.com/questions/13267126/how-to-get-name-of-second-last-folder-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!