简体   繁体   中英

Delete files that don't match a particular string format

I have a set of files that are named similarly:

TEXT_TEXT_YYYYMMDD

Example file name:

My_House_20170426

I'm trying to delete all files that don't match this format. Every file should have a string of text followed by an underscore, followed by another string of text and another underscore, then a date stamp of YYYYMMDD.

Can someone provide some advice on how to build a find or a remove statement that will delete files that don't match this format?

Using find , add -delete to the end once you're sure it works.

# gnu find
find . -regextype posix-egrep -type f -not -iregex '.*/[a-z]+_[a-z]+_[0-9]{8}'

# OSX find
find -E . -type f -not -iregex '.*/[a-z]+_[a-z]+_[0-9]{8}'

Intentionally only matching alphabetical characters for TEXT. Add 0-9 to each TEXT area like this [a-z0-9] if you need numbers.

grep -v '(pattern)'

will filter out lines that match a pattern, leaving those that don't match. You might try piping in the output of ls . And if you're particularly brave, you could pipe the output to something like xargs rm . But deleting is kinda scary, so maybe save the output to a file first, look at it, then delete the files listed.

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