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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 0means 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 1means process all files except the starting-points.
Method 2
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'
Method 3
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0