match all strings containing only one '/' character

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

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

@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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like