Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only find files in a given directory, and ignore subdirectories using bash

Tags:

bash

unix

People also ask

How do you list only files not directories in Linux?

Open the command-line shell and write the 'ls” command to list only directories. The output will show only the directories but not the files. To show the list of all files and folders in a Linux system, try the “ls” command along with the flag '-a” as shown below.

How do I search only directories in a specific directory?

You can use combination of ls command, find command, and grep command to list directory names only. You can use the find command too.

How do I exclude a directory in find?

We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command. The directory “bit” will be excluded from the find search!


If you just want to limit the find to the first level you can do:

 find /dev -maxdepth 1 -name 'abc-*'

... or if you particularly want to exclude the .udev directory, you can do:

 find /dev -name '.udev' -prune -o -name 'abc-*' -print

Is there any particular reason that you need to use find? You can just use ls to find files that match a pattern in a directory.

ls /dev/abc-*

If you do need to use find, you can use the -maxdepth 1 switch to only apply to the specified directory.


This may do what you want:

find /dev \( ! -name /dev -prune \) -type f -print

I got here with a bit more general problem - I wanted to find files in directories matching pattern but not in their subdirectories.

My solution (assuming we're looking for all cpp files living directly in arch directories):

find . -path "*/arch/*/*" -prune -o -path "*/arch/*.cpp" -print

I couldn't use maxdepth since it limited search in the first place, and didn't know names of subdirectories that I wanted to exclude.