简体   繁体   中英

delete files by date and the date is associated in filename using shell command

I am learning shell command, so this may be a trivial question. I have some files, file pattern is date-text1-text2.xml.gz

Example -

20140201-sometext1-sometext2.xml.gz

I want to delete files those have dates associated with it's name and that date is more than a specific value.

As of now, what I know is, I can find and delete files with some pattern, something like

find . -name "2014022*-sometext1-sometext2-*.xml.gz | xargs rm

This is going to find and delete files from 20140220 to 20140228. How I could I write the pattern so that it finds and delete all files starting from 20140220 till today. is this going to involve a more advanced scripting or can be done easily?

Notice that dates when printed with leading zeros (ie 01 for January) form a monotonic sequence of numbers. One simple way is to do the filtering in awk.

find . -type f -iname "20*" | awk -vFROM=20140110 '{ if (0+substr($1,3) >= FROM) print $1;}'

You find all files which match your pattern, set the smallest number you dont want to keep via the -v option to gawk and simply compare numbers. You can implement arbitrary filtering logic in your awk one-liner. The substr() chops of the './' part what find printed for the comparison. The 0+ craziness is there to make sure that awk does compare numbers not strings. Ugly, but sometimes necessary.

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