首页 > 解决方案 > 尝试使用正则表达式查找路径中的目录数

问题描述

我需要找出给定路径中有多少个目录。例如testdir1/testdir2/testdir3/应该返回三个目录,占最后一个/没有文本的目录。这一切都在 bash 环境中。

这是我尝试并想出的方法,并且有些工作,但是我得到了四个目录而不是三个:

tr '/.' '\n' <<< testdir1/testdir2/testdir3/ | wc -l

我将如何编写任务查找所有/,除了最后没有任何文本的那个

您的帮助将不胜感激。

标签: regexbash

解决方案


Using AWK

:=>echo "testdir1/testdir2/testdir3/"  | awk -F'/' '{ if ($NF =="") print NF-1; else NF }' 
3
:=>

Explanation:


awk -F'/'  -- Set field seprator as / 

{ if ($NF =="") -- NF is number of field in current record. $NF -- value is last field 
print NF-1; --  IF last field is empty print NF-1 else all fields 

Edit: Using grep

:=>echo "testdir1/testdir2/testdir3/"  | grep -o '/' |  wc -l 
3

推荐阅读