Skip to content

Instantly share code, notes, and snippets.

@andmax
Last active May 18, 2020 13:53
Show Gist options
  • Save andmax/8f7194b1aaa93ef0c2a88147bf7e5fc8 to your computer and use it in GitHub Desktop.
Save andmax/8f7194b1aaa93ef0c2a88147bf7e5fc8 to your computer and use it in GitHub Desktop.
Use double quotes for commands within variables and shell $expr for algebraic expressions within variables
#!/bin/bash
################################################################################
# The following is an explanation of the one-line command below:
# First grep to make sure the search string is present in the log file.
# Second do the sed -i (edit log file in place) by removing a range of
# lines defined in the double quotes. (Double quotes here are very important
# to allow to insert shell variables defined by dollar sign $ inside it.)
# The range of lines is from the first line to an L line number as "1,Ld".
# The line number L is defined by an algebraic expression N-2 as $(expr N - 2).
# (The spaces in-between elements inside the expression are very important.)
# The number N is defined by the line number in the log file itself where
# the log has written "| Starting at: <iso formmatted date of 15 days ago>" as
# $(date --date="15 days ago" -I) for the iso formatted date and as
# $(grep -n "| Starting at: <iso formatted date>" file.log to find the log line
# with the search string and precede it with its line number and a colon and as
# | cut -d : -f 1 to cut the actual log line after the line number delimitted
# by colon : and keep only the line number to be used as the number N.
################################################################################
grep -n "| Starting at: $(date --date="15 days ago" -I)" file.log && sed -i "1,$(expr $(grep -n "| Starting at: $(date --date="15 days ago" -I)" file.log | cut -d : -f 1) - 2)d" file.log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment