title: Remove all files with a common prefix except the N latest modified
body: <p>I am trying to create a bash command/script to remove all files in a directory older than X days that starts with a certain substring.</p>
  <p>For example, if our directory contains the files</p>
  <pre><code>-rw-r--r-- 1 root root 0 Jun 30 10:22 foo_5
  -rw-r--r-- 1 root root 0 Jun 29 10:22 bar_4
  -rw-r--r-- 1 root root 0 Jun 29 10:22 foo_4
  -rw-r--r-- 1 root root 0 Jun 28 10:22 bar_3
  -rw-r--r-- 1 root root 0 Jun 28 10:22 foo_3
  -rw-r--r-- 1 root root 0 Jun 27 10:22 bar_2
  -rw-r--r-- 1 root root 0 Jun 27 10:22 foo_2
  -rw-r--r-- 1 root root 0 Jun 26 10:22 foo_1
  </code></pre>
  <p>we want to delete all <code>foo*</code> files except the 2 most recent one. This will result in the directory</p>
  <pre><code>-rw-r--r-- 1 root root 0 Jun 30 10:22 foo_5
  -rw-r--r-- 1 root root 0 Jun 29 10:22 bar_4
  -rw-r--r-- 1 root root 0 Jun 29 10:22 foo_4
  -rw-r--r-- 1 root root 0 Jun 28 10:22 bar_3
  -rw-r--r-- 1 root root 0 Jun 27 10:22 bar_2
  </code></pre>
  <p>I am currently only able to delete all files except the 2 most recent, which will affect <code>bar*</code> files.</p>
  <pre><code>ls -t | tail -n +4 | xargs rm --
  </code></pre>
  <p>How can we also restrict our deletion to files that starts with a certain string?</p>
  <hr />
  <p><strong>Code to create test files</strong></p>
  <pre><code>(
  touch -d &quot;6 days ago&quot; foo_5
  touch -d &quot;7 days ago&quot; foo_4
  touch -d &quot;7 days ago&quot; bar_4
  touch -d &quot;8 days ago&quot; foo_3
  touch -d &quot;8 days ago&quot; bar_3
  touch -d &quot;9 days ago&quot; foo_2
  touch -d &quot;9 days ago&quot; bar_2
  touch -d &quot;10 days ago&quot; foo_1
  )
  </code></pre>