groovybear groovybear - 1 year ago 48
Bash Question

Can I replace hours in sed command with variable?

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:


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?


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 ==


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