Search code examples
regexgreppcre

Regex between last slash and next space in a set of strings in Bash


I've a bunch of strings in an output

adadds/asdsd/foo aeee/ggdgg/bar aff/ggg/ddafs/afdf/doo

From this I need the following list

foo
bar
doo

I tried the following but in vain:

(?<=\/)(.*?)(?=\s)

and

([/])(.*?)(?=\s)

Solution

  • Using gnu grep:

    s='adadds/asdsd/foo aeee/ggdgg/bar aff/ggg/ddafs/afdf/doo'
    grep -oP '[^/\s]+(?=\s|$)' <<< "$s"
    
    foo
    bar
    doo
    

    RegEx Details:

    • [^/\s]+: Match 1+ of any char that is not / and not a whitespace
    • (?=\s|$): Make sure we have either a whitespace or end of line ahead of current position

    If gnu grep is not available try this awk:

    awk '{for (i=1; i<=NF; ++i) {sub(/.*\//, "", $i); print $i}}' <<< "$s"