This will delete 159 days aged files recursively from the S3 bucket. You can change the days as per your requirement. which includes filenames with spaces. The above scripts didn't work with filenames with spaces.
Note: Existing directory structure may get deleted. If you don't prefer directory structure you can use this.
If you would prefer directory structure give the full path of last child directory and modify this on each execution to secure parent directory structure.
example:
s3://BucketName/dir1/dir2/dir3/
s3://BucketName/dir1/dir2/dir4/
s3://BucketName/dir1/dir2/dir5/
vim s3_file_delete.sh
s3bucket="s3://BucketName"
s3dirpath="s3://BucketName/WithOrWithoutDirectoryPath/"
aws s3 ls $s3dirpath --recursive | while read -r line;
do
createDate=`echo $line|awk {'print $1" "$2'}`
createDate=`date -d"$createDate" +%s`
olderThan=`date --date "159 days ago" +%s`
if [[ $createDate -lt $olderThan ]]
then
fileName=`echo $line|awk '{a="";for (i=4;i<=NF;i++){a=a" "$i}print a}' |awk '{ sub(/^[ \t]+/, ""); print }'`
if [[ $fileName != "" ]]
then
#echo "$s3bucket/$fileName"
aws s3 rm "$s3bucket/$fileName"
fi
fi
done;