On Sunday 1st of October 2017

Deleting files not matching in linux

Recently I wanted to delete files not starting with a certain prefixes in my Linux hosting server. There were several solutions proposed but the following code worked for me. The idea was to delete all files not starting with "large_" or "normal_" or "small_". 

Step 1: shopt -s extglob

This command enables some features of the terminal that are not enabled by default. The reference manual of "shopt" command specifies about the "extglob" parameter

If set, the extended pattern matching features described above (see Pattern Matching) are enabled.

Step 2: for d in ./*/ ; do (cd "$d" && rm !(@(large_*|normal_*|small_*))    ); done

The command goes throgh all the directories in the current path and execute a given command at each directory. In my case, I wanted to execute "rm !(@(large_*|normal_*|small_*))" command and it did the trick.

The original answers are here and here.