Search code examples
dateseddebiansh

How to filter results with sed using today's date


I'm asking because I can't find how to correctly use the sed function with the date function.

Context: I am concatenating log files into one with the cat function. So far so good. The date formats in the concatenated file might be: Feb 6, or 2022-02-07. I would like with the sed -i function to keep only the lines of the current date. I tried using the date function in the sed function:

  • sed -i '/^$(date +%b)d/;/$(date +%d)/d' XYZ.log
  • sed -i '/"$(date +%b)"/ from XYZ.log

I tried to use a variable in the sed function:

  • MONTH=$(date '+%b')
  • sed -i '/^"$MONTH"/ !d' XYZ.log

Both don't work.

Request: How to use the date function with the sed function in order to have in the XYZ.log file only the logs of the day?


Solution

  • The sed command is used to change text input; if you want to filter text you typically use the grep command, for instance like this:

    grep "^$(date +%Y-%m-%d)" XYZ.log