简体   繁体   English

如何在linux中获取倒数第二个文件夹的名称

[英]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.我必须在 linux 中编写一个 shell 脚本,我必须在其中提取给定路径的倒数第二个文件夹的名称。 For example:-例如:-

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

How can i get only the name of second last folder "folder2" using a command?如何使用命令仅获取倒数第二个文件夹“folder2”的名称?

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

Using awk:使用 awk:

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

Alternatively, call basename on the dirname .或者,在dirname上调用basename

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

you can use sed to get it:您可以使用 sed 来获取它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM