davidchambers
davidchambers

Reputation: 24806

Exclude specified directory when using `find` command

I have a directory which contains a number of files (no subdirectories). I wish to find these files. The following gets me close:

$ find docs
docs
docs/bar.txt
docs/baz.txt
docs/foo.txt

I don't want the directory itself to be listed. I could do this instead:

$ find docs -type f
docs/bar.txt
docs/baz.txt
docs/foo.txt

Using a wildcard seems to do the trick as well:

$ find docs/*
docs/bar.txt
docs/baz.txt
docs/foo.txt

My understanding is that these work in different ways: with -type, we're providing a single path to find, whereas in the latter case we're using wildcard expansion to pass several paths to find. Is there a reason to favour one approach over the other?

Upvotes: 0

Views: 196

Answers (2)

Vietnhi Phuvan
Vietnhi Phuvan

Reputation: 2804

find docs -type f

will get you a listing of every non-directory file of every subdirectory of docs

find docs/*

will get you a listing of every file AND every subdirectory of docs

Upvotes: 0

jim mcnamara
jim mcnamara

Reputation: 16379

You have a UNIX tag, and you example has a *. Some versions of find have a problem with that. If the directory has no subdirectories. FYI.

Generally the first parms to find has to be a directory or a list of directories

find /dir1 /dir2 -print

Find is recursive - so it will follow each directory down listing every thing, symlinks, directories, pipes, and regular files. This can be confusing. -type delimits your search

find /dir1 /dir2 -type f -print

You can also have find do extra output example: have it rm files older than 30 days for example:

find /dir1 /dir2 -type f -mtime +30 -exec rm {} \;

Or give complete infomation

find /dir1 /dir2 -type f -mtime +30 -exec ls -l {} \;
find /dir1 /dir2 -type f -mtime +30 -ls   # works on some systems

To answer your question: because find can be dangerous ALWAYS fully specify each directory , file type ,etc., when you are using a nasty command like rm. You might have forgotten your favorite directory is also in there. Or the one used to generate your paycheck. Using a wildcard is ok for just looking around.

Using *

find /path/to/files -type f -name 'foo*' 

-- tics or quotes around strings with a star in them in some UNIX systems.

Upvotes: 1

Related Questions