title: Is there a way to delete all log entries in a file older than a certain date? (BASH)
body: <p>I have log file in which I'm trying to delete all entries older than a specified date. Though I haven't succeeded with this yet. What I've tested so far is having an input for what the entries must be older than to be deleted and then loop like this:</p>
  
  <pre><code>#!/bin/bash
  
  COUNTER=7
  DATE=$(date -d "-${COUNTER} days" +%s)
  DATE=$(date -d -@${DATE} "+%Y-%m-%d")
  
  while [ -n "$(grep $DATE test.txt)" ]; do
  
      sed -i "/$DATE/d" test.txt
  
      COUNTER=$((${COUNTER}+1))
      DATE=$(date -d "-${COUNTER} days" +%s)
      DATE=$(date -d @${DATE} +"%Y-%m-%d")
  done
  </code></pre>
  
  <p>This kind of works except when a log entry doesn't exist for date. When it doesn't find a match it aborts the loop and the even older entries are kept.</p>
  
  <p><strong>Update</strong></p>
  
  <p>This was how I solved it:</p>
  
  <pre><code>#!/bin/bash
  
  COUNTER=$((7+1))
  DATE=$(date -d "-${COUNTER} days" +%s)
  DATE=$(date -d -@${DATE} "+%Y-%m-%d")
  
  if [ -z "$(grep $DATE test.txt)" ]; then
     exit 1
  fi
  
  sed -i "1,/$DATE/d" test.txt
  </code></pre>