在特定模式后将所有内容匹配到第一个'/' [英] match everything up to first '/' after a specific pattern

查看:47
本文介绍了在特定模式后将所有内容匹配到第一个'/'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在macOS上使用sed regex在bash脚本中执行此操作.我有一个带有外部驱动器目录列表的文件.

Trying to do this within a bash script using sed regex on macos. I have a file with directory listings of an external drive.

/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/

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

I want to search and return the top-most directory matching various patterns. If you search for 'Learning' the output should be:

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

推荐答案

这可能对您有用(GNU sed):

This might work for you (GNU sed):

sed -n 's/\(Learning[^/]*\/\).*/\1/p' file

使用-n选项关闭隐式打印.然后使用替换命令及其p标志在成功将字符串Learning替换为下一个出现的/时进行打印,并按\(...\)分组并引用\1(在替换中)为文件的末尾仅由反向引用\1组成.其他所有行将不会打印出来.

Turn off implicit printing by using the -n option. Then using the substitution command and its p flag to print on a successful replacement of the string Learning to the next occurrence of a /, grouped by \(...\) and referred to \1 (in the replacement) to the end of the file by the back reference \1 only. All other lines will not be printed out.

这篇关于在特定模式后将所有内容匹配到第一个'/'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆