Can any one please tell me the command that can be used to delete files of a particular extension such as .doc or .txt or .class etc from a folder or a directory on Linux? I want to delete the files together not individually though. Thanks a lot.

Dani AI

Generated

is right that a simple shell glob works. A few gotchas to keep in mind: the shell (not rm) expands the pattern, so unmatched globs can behave differently across shells, and globs typically do not match dotfiles unless the pattern starts with a dot. Also, deleting huge sets with a glob can hit the "argument list too long" limit. See the GNU docs for details on rm and pattern matching in Bash: rm invocation, Bash pattern matching.

For a safer, predictable approach that also handles recursion and very large sets, use find. Quote the pattern so the shell does not expand it before find sees it.

Preview (no deletion), current directory only:

find . -maxdepth 1 -type f -name '*.txt' -print

Delete, current directory only:

find . -maxdepth 1 -type f -name '*.txt' -delete

Recursive delete (all subfolders):

find . -type f -name '*.class' -delete

Multiple extensions or case-insensitive match:

find . -type f \( -name '*.txt' -o -name '*.doc' \) -delete
find . -type f -iname '*.doc' -delete

If you want a prompt for each file:

find . -type f -name '*.class' -ok rm -- {} \;

-delete is a GNU find action; for portability, replace it with:

find . -type f -name '*.txt' -exec rm -- {} +

These patterns include hidden files that match the extension, unlike most plain globs. Always double-check with -print first. References: GNU findutils manual.

Recommended Answers

All 2 Replies

rm *.<extension>

Hi,

Thanks a lot for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.