Linux – How to remove all files from a directory that have a certain filename length

bashlinuxrm

I have a tmp directory full of various files that a program has created and not cleaned up properly. Each of these files has a filename that's simply 6 random characters. In addition to these, there are a few dozen legitimate files in the directory that I do not want to delete. I could move these out and then rm -rf the entire directory, but I figured there would be an easier way as, conveniently, none of the legitimate files are of filename length 6.

Example:

-rw-------  1 root root    0 Sep  8 08:59 BxP6dX
-rw-------  1 root root    0 Sep  7 03:29 c93Rb2
-rw-------  1 root root    0 Sep  8 12:29 Cq8S3f
-rw-------  1 root root    0 Sep  8 03:59 CV_6kc
-rw-------  1 root root    0 Sep  7 15:29 d5cBqw
drwxr-xr-x  2 root root   40 Sep  6 16:03 legitimateFile
-rw-------  1 root root    0 Sep  7 21:29 qC5XQD
-rw-------  1 root root    0 Sep  9 04:59 Qid8Rt
-rw-------  1 root root    0 Sep  7 07:29 QIwMjT
-rw-------  1 root root    0 Sep  8 04:29 qp8J8H
-rw-------  1 root root    0 Sep  6 18:40 RcgcD3
-rw-------  1 root root    0 Sep  9 12:59 rIVtWR
-rw-------  1 root root    0 Sep  7 19:29 RpuePj
-rw-------  1 root root    0 Sep  8 17:59 rYJkh2
-rw-------  1 root root    0 Sep  8 09:59 S1WOSJ
-rw-------  1 root root    0 Sep  7 02:59 s3F0OA

Is there an easy way in bash to remove the randomly generated files?

Best Answer

You can use the ? wildcard to represent a single character.

So something like rm ?????? should remove all files with file names 6 characters long.

Related Question