Search code examples
linuxbashglob

Deleting files ending with 2 digits in linux


In my folder, I want to delete the files that ends with 2 digits (10, 11, 12, etc.)

What I've tried is

rm [0-9]*

but it seems like it doesn't work.

What is the right syntax of doing this?


Solution

  • Converting comments into an answer.

    Your requirement is a bit ambiguous. However, you can use:

    rm -i *[0-9][0-9]
    

    as long as you don't mind files ending with three digits being removed. If you do mind the three-digit files being removed, use:

    rm -i *[!0-9][0-9][0-9]
    

    (assuming Bash history expansion doesn't get in the way). Note that if you have file names consisting of just 2 digits, those will not be removed; that would require:

    rm -i [0-9][0-9]
    

    Caution!

    The -i option is for interactive. It is generally a bad idea to experiment with globbing and rm commands because you can do a lot of damage if you get it wrong. However, you can use other techniques to neutralize the danger, such as:

    echo *[!0-9][0-9]
    

    which echoes all the file names, or:

    printf '%s\n' *[!0-9][0-9]
    

    which lists the file names one per line. Basically, be cautious when experimenting with file deletion — don't risk making a mistake unless you know you have good backups readily available. Even then, it is better not to need to use them

    See also the GNU Bash manual on: