Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

Example:

/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

1 Answer 1

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"
    fi
done

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.