match everything up to first '/' after a specific pattern

家住魔仙堡 提交于 2020-02-25 04:46:29

问题


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/

回答1:


This might work for you (GNU sed):

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

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.




回答2:


In case you are ok with awk could you please try following.

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

Output will be as follows.

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


来源:https://stackoverflow.com/questions/59163753/match-everything-up-to-first-after-a-specific-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!