Score:1

Searching for and deleting files with a certain extension or ending with a number

cn flag

I'd like my script to find a certain file type and delete it.

I know that find path/to/directory/ -type f -name '*.ext' -delete will find and delete all files with the extension.

Now I'd also like to have my script remove any file ending with a number regardless of the extension, as well as the files ending with the extension.

I tried the following commands with no success:

find path/to/directory/ -type f -name '*.ext' -name '*[0-9].* -delete
find path/to/directory/ -type f -name '*.ext' '*[0-9].* -delete
find path/to/directory/ -type f -name '*.ext,*[0-9].* -delete

None of these worked, I'm not sure what exactly I need to change or what I am doing wrong.

Score:1
hr flag

remove the files ending with extension as well as any file ending with a number regardless of the extension

That requires conditions joined by logical OR instead of the default logical AND (parentheses are required because OR has lower precedence than AND, and they must be escaped or quoted so that the shell passes them to find as literals):

find path/to/directory/ -type f \( -name '*.ext' -o -name '*[0-9].*' \) -print

Change -print to -delete once you are certain that it's doing the right thing. In the GNU implementation of find, you may use -or in place of -o if you prefer.

Mahmoud avatar
cn flag
thank you for the quick respond, I'm fairly new to scripting, I suppose -o means "or" but why do I need the \ in this?
hr flag
@Mahmoud the parentheses must be escaped `\(` or quoted `'('` so that the shell passes them to `find` as literals
Mahmoud avatar
cn flag
so I could write this ```\( -name '*.ext' -o -name '*[0-9].*' \)``` like this instead ```'( -name '*.ext' -o -name '*[0-9].*' )'``` correct?
hr flag
@Mahmoud no, each individual `(` or `)` needs to be quoted as a separate token `'(' -name '*.ext' -o -name '*[0-9].*' ')'`
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.