Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to delete all .exe files in the current folder and all the sub-folders.

I read that find . -name "*.exe" -exec rm -f '{}' \; will do, but I want to do the delete only if the container folder has the same name as the .exe.


/me/folder1/folder1.exe    - delete folder1.exe
/me/folder 2/folder 2.exe  - delete 'folder 2.exe'
/me/folder3/otherexe.exe   - do not delete otherexe.exe
share|improve this question

Run this in Bash. It iterates over all .exe files and compares the parent directory name against the filename (without extension).

shopt -s extglob
for f in **/*.exe; do
    dir="$(basename "$(dirname "$f")")"  # get dirname
    file="$(basename "${f%.*}")"         # get filename, without extension
    if [ "$dir" = "$file" ]; then
        rm -i -- "$f"

The trick to get the raw directory name is to call basename on the dirname of the file. All substitutions need to be quoted though to make this command work with file names containing whitespace.

If you do not want to be prompted before removing files, remove the -i option for the rm call.

share|improve this answer
Sorry, but shall I save it in a file then run, or just copy/paste on the terminal? – xthink Sep 10 '13 at 10:43
You can just copy-paste this entire piece of code from your current working directory. You can, of course, also save it in a shell script, but that's not really needed. – slhck Sep 10 '13 at 10:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .