首页 > 解决方案 > 匹配特定模式后的第一个'/'

问题描述

尝试在 bash 脚本中使用 sed 正则表达式在 macos 中执行此操作。我有一个包含外部驱动器目录列表的文件。

/Volumes/WD/A/Some Learning/Learning Is Great/
/Volumes/WD/A/Some Deeper/Learning Is Great/Another Learning Opportunity/
/Volumes/WD/B/More Things Here/Great Learning/
/Volumes/WD/B/More Things/

我想搜索并返回匹配各种模式的最顶层目录。如果您搜索“学习”,则输出应为:

/Volumes/WD/A/Some Learning/
/Volumes/WD/A/Some Deeper/Learning Is Great/
/Volumes/WD/B/More Things Here/Great Learning/

标签: regexawksed

解决方案


如果您觉得awk可以,请尝试以下操作。

awk 'match($0,/Learning[^\/]*\//){print substr($0,1,RSTART+RLENGTH-1)}' Input_file

输出如下。

/Volumes/WD/A/Some Learning/
/Volumes/WD/A/Some Deeper/Learning Is Great/
/Volumes/WD/B/More Things Here/Great Learning/

推荐阅读