问题
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