delete all the files having similar pattern whose date is less than particular date

StackOverflow https://stackoverflow.com/questions/14676462

  •  06-03-2022
  •  | 
  •  

سؤال

I am trying to delete files from the Unix directory which starts with EXPORT_v1x0 and whose date is less than 2013-01-25 (Jan 25th 2013). I can delete the files one by one but it will take few days for me to delete all the files. Is there any better way to delete the files with the specific pattern?

Below are the sample files when I do ls

bash-3.00$ ls /data/bds/real
EXPORT_v1x0_20120811.dat.gz 
EXPORT_v1x0_20120811.dat.gz   

If you see the above files. Each file has a date in that. Suppose we take this file into the consideration-

EXPORT_v1x0_20120811.dat.gz

It's date is 20120811 So I need to delete all the files which starts with EXPORT_v1x0 and whose date is less than 20130125. So If I am supposed to delete all the files having date less than 20130125 then all the files above I mentioned will get deleted as there dates are less than 20130125.

NOTE:- All the files are having same pattern exactly as I mentioned above. Only date and other numbers followed by that are different.

So I just need to delete all the files which starts with EXPORT_v1x0 and whose date is less than 20130125.

I am running SunOS. I am still in the process of learning Unix better. So not sure of any high ends commands and scripts.

هل كانت مفيدة؟

المحلول

A first naive approach to the problem, tweek it to your needs:

find . | awk -F'_' '$3<20130125' | xargs rm

To prevent find from doing a recursive search and just stay in current folder:

find . \( ! -name . -prune \) -type f | ...

2nd update:

Add the name parameter to only list files that contains the string "EXPORT_v1x0"

find . \( ! -name . -prune \) -type f -name "EXPORT_v1x0*" | ...

Simpler way to make find non-recursive is to use the maxdepth flag

find . -maxdepth 1 -type f -name "EXPORT_v1x0*" | ...

نصائح أخرى

WARNING: Be very careful

You list the files that you want like this:

ls -1 | awk -F _ '$3<"20130125"'

if that gives the proper list of files, you can do

ls -1 | awk -F _ '$3<"20130125"' | xargs rm
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top