24

Having trouble listing the contents of a folder I'm not in, while excluding the actual folder name itself.

ex:

root@vps [~]# find ~/test -type d
/root/test
/root/test/test1

However I want it to only display /test1, as the example.

Thoughts?

cbcp
  • 339
  • 2
  • 6
  • 12

4 Answers4

41

There's nothing wrong with a simple

find ~/test -mindepth 1

Similarly, this will have the same effect:

find ~/test/*

as it matches everything contained within ~/test/ but not ~/test itself.

As an aside, you'll almost certainly find that find will complain about the -mindepth n option being after any other switches, as ordering is normally important but the -(min|max)depth n switches affect overall behaviour.

sanmiguel
  • 4,580
  • 1
  • 30
  • 27
  • 3
    also you can just list the folders and files of that folder with '-maxdepth 1 -mindepth 1' – kommradHomer Dec 11 '13 at 10:19
  • 1
    Using `-mindepth` is good, but don't use the wildcard version because it may fail if the maximum command argument size is exceeded. – Curt Jul 29 '16 at 00:44
  • `-mindepth` is nice, but I'd like to keep folders that have no subdirectories. Do you know how this can be done? – danijar Aug 20 '16 at 00:02
  • 1
    There's at least one practical difference between `-mindepth 1` and adding `/*`. Mindepth matches top level dot files like `~/test/.env`, while /* will not. See example here http://stackoverflow.com/a/28809662/490592 – Chad von Nau May 03 '17 at 06:48
7

You can do that with -exec and basename:

find ~/test -type d -exec basename {} \;

Explanation:

  • The find ~/test -type d part finds all directories recursively under ~/test, as you already know.
  • The -exec basename {} \; part runs the basename command on {}, which is where all the results from the last step are substituted into.
sampson-chen
  • 45,805
  • 12
  • 84
  • 81
3

Then you need -type f instead of -type d.

Or, if you want to display list of folders, excluding the parent -mindepth 1 (find ~/test -type d -mindepth 1).

And now that you edited it, I think what you want may be

find ~/test -type d -mindepth 1 |cut -d/ -f3-

But I think you need to be more specific ;-)

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • ...then it would only list files. -type d is for directory. I'm simply trying to exclude the parent from it, As if I'm in the directory/ – cbcp Nov 14 '12 at 18:28
  • @cbcp, yes, I realized that I might have misread you (actually, was mostly basing my answer on example, not the prose). See the updated answer. – Michael Krelin - hacker Nov 14 '12 at 18:29
-1

I just fixed it with sed

find $BASE -type d \( ! -iname "." \)|sed s/$BASE//g

Where $BASE is initial foldername.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
cbcp
  • 339
  • 2
  • 6
  • 12