简体   繁体   中英

How to recursively delete all files in folder that dont match a given pattern

I would like to delete all files in a given folder that dont match the pattern ^transactions_[0-9]+

Let's say I have these files in the folder

file_list
transactions_010116.csv
transactions_020116.csv
transactions_check_010116.csv
transactions_check_020116.csv

I would like to delete transactions_check_010116.csv and transactions_check_020116.csv and leave the first two as they are using ^transactions_[0-9]+

I've been trying to use find something like below, but this expression deletes everything in the folder not just the files that dont match the pattern:

find /my_file_location -type f ! -regex '^transactions_[0-9]+' -delete

What i'm trying to do here is using regex find all files in folder that dont start with ^transactions_[0-9]+ and delete them.

grep具有-v选项以grep与提供的正则表达式不匹配的所有内容:

find . | grep -v '^transactions_[0-9]+'  | xargs rm -f

Depending on your implementation, you could have to use option -E to allow the use of full regexes. An other problem is that -regex gives you an almost full path starting with the directory you passed.

So the correct command should be:

 find -E /my_file_location ! -regex '.*/transactions_[0-9]+$' -type f -delete

But you should first issue the same with -print to be sure...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM