I have a very long file containing file paths, one on each line. I would like to retrieve a list of all directories listed which are only 1-level deep. As such, I would like to extract only those lines which have a single / in them:

I want: ./somedir
I don't want: ./somedir/someotherdir

Can I do this with grep and/or regular expressions?


Sure. That's pretty easy:

find . | grep -P '^\./[^/]*$'

... where obviously the 'find' command I'm using just to illustrate what you described. The regex works as follows:

  • ^ and $ are anchors specifying (respectively) the beginning & end of the line. All content must be between those two characters
  • \./ is a literal period followed by a literal forward-slash
  • [^] is a character-class that disallows anything after the ^ and before the ]
  • The * after [^/] says to allow zero or more occurrences of that character class

You could also do it like this:

dosomething | grep -P '^[^/]*/[^/]*$'

This will allow only a single / on the line, in any position on the line (even first or last character).

  • 1
    As an aside, the example you gave with the ./ leads me to believe you're generating a list with find. Assuming that's the case, you can do something like this: find . -maxdepth 1 (other conditions). – Brian Vandenberg May 10 '11 at 16:17

@Brians solution works, this is a more generic one that doesn't need a ./ at the beginning:

grep -P '^[^/]*/[^/]*$'

For example:


--> somedir/otherdir
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.