-2

I want to print all the lines between line that contains "ABC" and an empty line.

awk '/ABC/,/^$/' file

This works fine

I want to put ABC in to a variable.So I pass it to awk as follows

awk -v targetLine='ABC' '/targetLine/,/^$/' file

This doesnt return me anything.

Can someone help whats wrong in here, why my variable is not getting picked up.

vibz
  • 157
  • 1
  • 12
  • 1
    Does this answer your question? [How to use awk variables in regular expressions?](https://stackoverflow.com/questions/11534173/how-to-use-awk-variables-in-regular-expressions) – Wiktor Stribiżew Jul 21 '20 at 08:30
  • You meant this line "Secondly, awk will not interpolate what's between // -- that is just a string in there" ? – vibz Jul 21 '20 at 08:41

2 Answers2

1

An awk program is composed of pairs of

 pattern { action }

where action is executed when pattern creates a non-zero/non-empty value. One of the possible patterns is a pattern range. A pattern-range is nothing more then two patterns which are comma separated.

pattern1 , pattern2 { action }

While most people write it down using ERE tokens such as:

/foo/,/bar/ { action }

the patterns can be anything which represents a valid pattern, other examples could be:

(FNR==3),$0=="foo" {action}  or (index($2,"foo")>2),(FNR%5==4) {action}

So based on this, we can just answer your question as:

awk -v ere="ABC" '($0 ~ ere),/^$/'

However, be aware that from the moment you want to slightly change your code, using pattern-ranges, you generally have to do a full rewrite (See Is a /start/,/end/ range expression ever useful in awk?): So it might be better just to write:

awk -v ere="ABC" '($0 ~ ere){f=1};f;/^$/{f=0}'
kvantour
  • 25,269
  • 4
  • 47
  • 72
0

This is a way to pass the variable in AWK without using the '-v' option:

var="ABC"
awk '/'"$var"'/,/^$/' file

And with '-v' option:

var="ABC"
awk -v a=$var '$0 == a,/^$/' file
mchelabi
  • 154
  • 5