Search code examples
regexgreppcre

Can I perform a 'non-global' grep and capture only the first match found for each line of input?


I understand that what I'm asking can be accomplished using awk or sed, I'm asking here how to do this using GREP.

Given the following input:

.bash_profile
.config/ranger/bookmarks
.oh-my-zsh/README.md

I want to use GREP to get:

.bash_profile
.config/
.oh-my-zsh/

Currently I'm trying

grep -Po '([^/]*[/]?){1}'

Which results in output:

.bash_profile
.config/
ranger/
bookmarks
.oh-my-zsh/
README.md

Is there some simple way to use GREP to only get the first matched string on each line?


Solution

  • I think you can grep non / letters like:

    grep -Eo '^[^/]+'
    

    On another SO site there is another similar question with solution.