76

Using /bin/find /root -name '*.csv' returns:

/root/small_devices.csv
/root/locating/located_201606291341.csv
/root/locating/located_201606301411.csv
/root/locating/g_cache.csv
/root/locating/located_201606291747.csv
/root/locating/located_201607031511.csv
/root/locating/located_201606291746.csv
/root/locating/located_201607031510.csv
/root/locating/located_201606301412.csv
/root/locating/located_201606301415.csv
/root/locating/located_201607031512.csv

I don't actually want all the files under /root/locating/, so the expected output is simply /root/small_devices.csv.

Is there an efficient way of using `find' non-recursively?

I'm using CentOS if it matters.

DeepSpace
  • 979

3 Answers3

103

You can do that with -maxdepth option:

/bin/find /root -maxdepth 1 -name '*.csv'

As mentioned in the comments, add -mindepth 1 to exclude starting points from the output. From man find:

-maxdepth levels

Descend at most levels (a non-negative integer) levels of directories below the starting-points. -maxdepth 0 means only apply the tests and actions to the starting-points themselves.

-mindepth levels

Do not apply any tests or actions at levels less than levels (a non-negative integer).
-mindepth 1 means process all files except the starting-points.

Sundeep
  • 12,008
  • 6
    You may sometimes want to also specify -mindepth 1. For example, find /csv -maxdepth 1 -name '*csv' includes /csv (which has a depth of 0) in its output, whereas find /csv -mindepth 1 -maxdepth 1 -name '*csv' does not. – ma11hew28 Sep 29 '20 at 19:04
14

With standard find:

find /root ! -path /root -prune -type f -name '*.csv'

This will prune (remove) all directories in /root from the search, except for the /root directory itself, and continue with printing the filenames of any regular file that matches *.csv.

With GNU find (and any other find implementation that understands -maxdepth):

find /root -maxdepth 1 -type f -name '*.csv'

If you only want to prune the path /root/locating:

find /root -path /root/locating -prune -o -type f -name '*.csv' -print

Now, all subdirectories under /root are entered, except for the specific subdirectory /root/locating.

Note that you can't do this with the -maxdepth option.

Kusalananda
  • 333,661
4

You can use the -maxdepth and -mindepth primaries:

find /root -maxdepth 1 -mindepth 1 -name '*.csv'

With FreeBSD find (used by macOS) you might be tempted to use -depth 1 instead of -maxdepth 1 -mindepth 1, but that would be inefficient, since as Stéphane Chazelas comments below,depth 1 "doesn't stop find from descending into directories of depth greater than 1", as does -maxdepth 1. GNU find doesn't support -depth n.

ma11hew28
  • 141