1

I want to remove all png images in particular directory.

I there are following directories and images, how can I remove all png files at once?

.
├── 1
│   ├── 2
│   │   ├── 3
│   │   └── 3.png
│   └── 2.png
└── 1.png

I tried following command.

rm -rf *.png       #only 1.png was deleted.
rm -rf **/*.png    #only 2.png was deleted.
rm -rf **/**/*.png #only 3.png was deleted.
lc.
  • 113,939
  • 20
  • 158
  • 187
Tetsu
  • 213
  • 2
  • 11

3 Answers3

3

You need to set the globstar option (introduced in Bash 4) for the recursive globbing to work

From the Bash reference manual

globstar

    If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match.

So this should work

shopt -s globstar
rm -f **/*.png

Or alternatively with find and the delete action

find . -name '*.png' -delete

Note on the "-r" switch of rm:

-r switch "remove directories and their contents recursively" (Source: man rm). By default, rm can't remove directories. The switch doesn't change how filename expansion or globbing works.

Community
  • 1
  • 1
doubleDown
  • 8,048
  • 1
  • 32
  • 48
0

find . -name \*.png | xargs rm

Joe Z
  • 17,413
  • 3
  • 28
  • 39
0
find . -name "*.png" -exec rm -rf {} \;

This post has a very similar question: How do I remove all .pyc files from a project?

Community
  • 1
  • 1
Brian
  • 3,453
  • 2
  • 27
  • 39
  • You probably do not want `-r` since that only applies to directories, and you only want to operate on files with this particular exercise. – Joe Z Jul 06 '13 at 17:20