0

Our log pattern is in the following format dd/Mon/year:time(22/Feb/2018:13).

Goal is we want to find logs between 2 different times. We used sed to get the log between 2 times.

 sed -n '/22\/Feb\/2018:13:/,/22\/Feb\/2018:16/p' /var/log/apache2/domlogs/access.log

The above command is working manually. We created a two variables called LAST and NOW in the script and assigned the date variables as mentioned below.

NOW="22/Feb/2018:16"

LAST="22/Feb/2018:13"

We have used the following sed commands to print the same output however it doesn't help us to print the same output.

sed -n '/'"$LAST"'/'"$NOW"'/p' /var/log/apache2/domlogs/access.log

The command gives the below error sed: -e expression #1, char 5: unknown command: `F'

If we use normal string for LAST and NOW then above command works fine. Only problem is if the variable contains / in the input

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern – zzxyz Feb 22 '18 at 18:45
  • 1
    Yes; you aren't passing variables to a `sed` script, you are dynamically *creating* a `sed` script, so it is your responsibility to escape anything in the values of `NOW` and `LAST` so that the resulting script is valid. – chepner Feb 22 '18 at 18:51

1 Answers1

0

You can freely change your delimiter of sed's regular expression by preceding it with a backslash, e.g. \!. Following command should work:

sed -n '\!'"$LAST"'!,\!'"$NOW"'!p' /var/log/apache2/domlogs/access.log

If ! is expected to show up in your date time format, you can use your judgment to choose another one.

You should read some good sed tutorial before working with sed, e.g.: http://www.grymoire.com/Unix/sed.html


I think you originally want to implement a range search in sed while you might miss the syntax of that. I fixed it above and it's tested.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41