Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 4 down vote accepted

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).

share|improve this answer
thanks! that's exactly what I needed – Mala May 10 '11 at 16:12
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
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .