2

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?

2 Answers 2

6

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
  • 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). Commented May 10, 2011 at 16:17
2

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

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

For example:

/aa/somedir
test/somedir/someotherdir
somedir/otherdir

--> somedir/otherdir

You must log in to answer this question.

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