regex - 尝试使用正则表达式查找路径中的目录数
问题描述
我需要找出给定路径中有多少个目录。例如testdir1/testdir2/testdir3/
应该返回三个目录,占最后一个/
没有文本的目录。这一切都在 bash 环境中。
这是我尝试并想出的方法,并且有些工作,但是我得到了四个目录而不是三个:
tr '/.' '\n' <<< testdir1/testdir2/testdir3/ | wc -l
我将如何编写任务查找所有/,除了最后没有任何文本的那个?
您的帮助将不胜感激。
解决方案
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
推荐阅读
- java - 识别 Windows AD 远程用户 Spring Boot + Waffle
- javascript - 如何通过保留默认值来删除javascript中的键数组
- ramda.js - Ramda.js - 如何查看嵌套数组中的多个值
- mysql - 不正确的字符串值:mySql 中第 1 行的列 \'description\' 的 \'\\xC3\'
- javascript - 在数组对象上反应映射
- javascript - 如何在chrome中查看javascript代码?
- c++ - 为什么我不能从 char* 构造 wstring
- javascript - Aria-live 内容被 Mac 读取两次 - Chrome - VoiceOver
- google-sheets - google sheet image() 函数更新(缓慢、不稳定、滞后)
- python - CheckboxGroup、散景、堆积条形图