<p>I have a total of 2030 pvc's and I want to delete 2000 pvc's form them and keep the 30.</p>
<ul>
<li><p>Those 30 pvc's are latest and only less that 2 days old.. so that is why I do not want to delete them. The other all 2000 pvc are more than 2 days old.</p>
</li>
<li><p>I want to create a script that runs automatically to delete the pvc's which are more than 2 days old.</p>
</li>
</ul>
<p>some example of my pvcs:</p>
<pre><code>NAME                            STATUS        VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   AGE
data-14353-postgresql-0         Bound         pvc-1a6   8Gi        RWO            gp2            2d15h
data-14354-postgresql-0         Bound         pvc-2d6   8Gi        RWO            gp2            16d
data-14358-postgresql-0         Bound         pvc-9dc   8Gi        RWO            gp2            127m
data-14367-postgresql-0         Bound         pvc-2eb   8Gi        RWO            gp2            65h
data-14370-postgresql-0         Bound         pvc-90d   8Gi        RWO            gp2            56d
</code></pre>
<p>now as u can see I have a mixed AGE label.</p>
<p>They can be deleted using:</p>
<pre><code>kubectl delete pvc 
</code></pre>
<p>but this will delete all.. and I do not want to delete all!</p>
<ul>
<li>what command or -label for age I can add to run the command to delete all pvc except those with less than 2 days old.</li>
</ul>

<p>TL:DR;</p>
<pre><code>kubectl get pvc --sort-by=.metadata.creationTimestamp --no-headers | tac | cut -d ' ' -f 1 | sed -n 31,2000p | xargs kubectl delete pvc
</code></pre>
<p>Let's explain in pieces:</p>
<ul>
<li><p><code>kubectl get pvc --sort-by=.metadata.creationTimestamp --no-headers</code>:</p>
<p>This part lists the PVCs in descending order without the header row</p>
</li>
<li><p><code>tac</code></p>
<p>reverse the output and produce ascending order</p>
</li>
<li><p><code>cut -d ' ' -f 1</code></p>
<p>Get's the first column which have the PVCs names</p>
</li>
<li><p><code>sed -n 31,2000p</code></p>
<p>Prints all the PVCs after line 30 which will contain your 30 PVCs which are less that 2 days old</p>
<blockquote>
<p>p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.</p>
</blockquote>
<blockquote>
<p>n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands.</p>
</blockquote>
</li>
<li><p><code>xargs kubectl delete pvc</code></p>
</li>
</ul>
<p>Deletes your PVCs.</p>
