Problem with syntax using awk

Hi Guys,
When below code is executed in script, I get desired output in output file.

awk 'NR >= $start_line  && NR <= 3' master_scriptlist.txt > $driver1/scriptlist.txt

But when i replace 3 with a variable end_line=3, I do not get ouput. See code below. Is there any problem with syntax

awk 'NR >= $start_line  && NR <= $end_line' master_scriptlist.txt > $driver1/scriptlist.txt

You need to quote your variable this way:

awk 'NR >= '"$start_line"'  && NR <= '"$end_line"'' master_scriptlist.txt > $driver1/scriptlist.txt

---------- Post updated at 08:51 AM ---------- Previous update was at 08:45 AM ----------

But I am curious how the code above works...

I prefer

awk -vstart=$start_line -vend=$end_line 'NR >= start  && NR <= end ' master_scriptlist.txt > $driver1/scriptlist.txt

The action to take when the condition is true is omitted and by default implies that $0 is printed. Longer form, which might be more understandable, would be:

awk '
   NR >= $start_line  &&  NR <= 3 { 
        print;
   }' master_scriptlist.txt > $driver1/scriptlist.txt

@rdcwayx -- I'm with you on that 100%. Stitching together quoted segments to incorporate shell variables will end badly at some point in time.

I know that, I am just wondering how the code works while the "$start_line" variable is inserted directly into the awk code, I think this is undefined, and the code does not work here.

Yea, it is much better to use -v option, I learned something, thank you.

Sorry, didn't mean to insult you :slight_smile:

I see what you are saying (in addition to the typo that I cut/pasted into my example). It's possible that awk is interpreting $start_line as 0, which would always be true, but I cannot reproduce it, so I'm not sure.

Thank you for responding.

Could you please answer these questions

  1. When do we enclose quotes (" ") within a variable?
  2. When do we enclose quotes (` `) within a variable?
  3. When do we enclose both the above quotes within a variable?

For eg

awk 'NR >= '"$start_line"'  && NR <= '"$end_line"'' master_scriptlist.txt > $driver1/scriptlist.txt