Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to use range patterns in awk:

grep -a volume somefile | awk '/^Apr 25 23:44:04*/,/^Apr 26 12:44:01*/ {print}'

This works fine, but when I try to execute it by putting the date and time in variables and execute it doesn't seem to work:

time1="Apr 25 23:44:04"
time2="Apr 26 12:44:01"
grep -a volume somefile | awk '/^"$time1"*/,/^"$time2"*/ {print}'
share|improve this question

Because the shell variables inside a single-quoted string, they will not be expanded. It doesn't matter that the single-quoted string includes double-quotes inside of it, it is still a single-quoted string.

Use instead:

grep -a volume somefile | awk "/^$time1/,/^$time2/ {print}"

Actually, since print is the default action, one can simplify that to:

grep -a volume somefile | awk "/^$time1/,/^$time2/"

You do need to be careful with this approach. You must make sure that neither time1 nor time2 contain unintentional awk-active characters.

A safer approach is to transfer the shell variables to awk variables:

grep -a volume somefile | awk -v t1="$time1" -v t2="$time2" '($0~"^"t1),($0~"^"t2)'

Note that, even in this safer approach, as Gilles notes in the comments, you still must be careful: if the strings in time1 and time2 were to contain the characters ^*+.?\[|{$, the strings would be interpreted as regular expressions. This is not a problem for the strings shown in the question (they contain no regex-active characters) but, if other strings were to give you surprising results, this is a likely cause.

share|improve this answer
    
Note that your safer approach is still not safe. If time1 and time2 contain any of *+.?\[|{, they will be interpreted as regexp metacharacters. – Gilles May 1 '15 at 21:08
    
@Gilles Good point. I added mention of the issue of regex-active characters to the answer. – John1024 May 1 '15 at 21:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.