groovybear groovybear - 6 months ago 13
Bash Question

Can I replace hours in sed command with variable? [Case Closed]

I'm trying to get a certain timestamps (in my case every 15 minute) in logfile using sed command in bash scripting.

My question is, can I replace the hours in the command with a variable?

This is script that I want:

#!/bin/bash

hour=`date +%H` #Current Hours e.g 14:00

sed -n '/$hour:15:00/,/$hour:30:00/p' file.log | nice grep Event


The result will print the logfile from 14:15:00 until 14:30:00. But there's a problem when the range is from 45 minute to 60 minute which is 14:45 - 15:00. Is there any solution for this?

UPDATE

This issue is already solved, the command below work for me.

sed -n "/${hour}:15:00/,/${hour}:30:00/p" file.log | nice grep Event


Other reference: Replace a string in shell script using a variable

Thank you.

== Case closed ==

Answer

Well, to answer the question - yes, you would take the variable out of the quotes and then it should use the value:

sed -n '/'$hour:15:00/,/'$hour':30:00/p' file.log | nice grep Event

You could also just use double quotes around the expression

sed -n "/${hour}:15:00/,/${hour}:30:00/p" file.log | nice grep Event
Comments