0

These are files in my home directory:

23233.txt
3233.txt
ba233.txt
kh23.txt
khalith
main.sh
s2233.txt
tr233.txt
WWW.txt

How may I remove all files whose names start with two lower-case letters, followed by two digits and the extension .txt, e.g. kh23.txt?

2 Answers 2

4

The pattern you may be looking for is

[a-z][a-z][0-9][0-9].txt

This will match any name in the current directory consisting of exactly two lowercase characters, followed by two digits, followed by the literal string .txt.

Filename globbing patterns are, unlike regular expressions, automatically anchored to the start and end of the string, so we don't have to say anything special about the filenames not having characters before the first of the two lowercase character or after the .txt.

You may either use this pattern with rm directly:

$ rm "$HOME"/[a-z][a-z][0-9][0-9].txt

or, if you want to recurse down into all subdirectories, with find:

$ find "$HOME" -name "[a-z][a-z][0-9][0-9].txt" -delete

If your implementation of find does not support -delete, consider the following instead:

$ find "$HOME" -name "[a-z][a-z][0-9][0-9].txt" -exec rm {} +

PS: Use the word digit when you mean a number between zero and nine. A number is a bit vague, especially since 233, which is part of several of the example filenames, is a number. (I have since edited the question to remove this ambiguity)

3
  • Thank you for your response. find -regextype posix-extended -regex '.*/[a-z]{2}[0-9]{2}\.txt' this works for me :) Jun 16, 2017 at 13:59
  • Even this command works fine.. find -name "[a-z][a-z][0-9][0-9].txt" -exec rm {} \; Jun 16, 2017 at 14:02
  • @KhalithBasha Good. Notice that you will have to either be in your home directory, or give find the home directory to search, to be able to find the files in your home directory.
    – Kusalananda
    Jun 16, 2017 at 14:04
1

What about this?

find /path/to/parent/dir/ -regextype posix-extended -regex '.*/[a-z]{2}[0-9]{2}\.txt' -exec rm {} \; 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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