match all strings containing only one '/' character

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?

Mala

Posted 2011-05-10T15:55:28.167

Reputation: 5 998

Answers

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

Brian Vandenberg

Posted 2011-05-10T15:55:28.167

Reputation: 504

1As 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 – 2011-05-10T16:17:11.197

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

slhck

Posted 2011-05-10T15:55:28.167

Reputation: 182 472