fazlin wrote:
> On Dec 26, 8:15 pm, Janis Papanagnou <Janis_Papanag...@[EMAIL PROTECTED]
>
> wrote:
>
>>fazlin wrote:
>>
>>>Hello All,
>>
>>>I have an input file "myfile" and a shell variable "VAR" whose
>>>contents are shown below:
>>
>>># cat myfile
>>>Hello World
>>>Hello Universe
>>># echo $VAR
>>>World
>>
>>>I need to process all lines in "myfile" which contains pattern "World"
>>>using awk. It works if i do as shown below:
>>
>>># awk '/World/ { print $0 }' myfile
>>
>>>But i could not use VAR to do the same operation. I tried the
>>>following even knowing that these will not work:
>>
>>># awk '/$VAR/ { print $0 }' myfile
>>
>>>and
>>
>>># awk -v lvar=$VAR '/lvar/ { print $0 }' myfile
>>
>>>and
>>
>>># awk -v lvar=$VAR 'lvar { print $0 }' myfile
>>
>> awk -v lvar=$VAR '$0~lvar { print $0 }' myfile
>>
>>or, since print $0 is the default, just
>>
>> awk -v lvar=$VAR '$0~lvar' myfile
>>
>>(Though, there are some caveats using patterns in variables, if
>>they contain special pattern meta characters and not only text.)
>>
>>Janis
>>
>>
>>
>>
>>
>>
>>>Please let me know how to match the contents of VAR in awk.
>>
>>>Thanks in advance,
>>>Fazlin- Hide quoted text -
>>
>>- Show quoted text -- Hide quoted text -
>>
>>- Show quoted text -
>
>
> Thanks for your reply. I have another query. Is there any way by which
> i can use lvar inside // ?
(That's more of an OS/shell question than awk...)
You can do that, but I would not recommend it. You would have to fiddle
around with quoting, as in
awk '/'$var'/{print "Hello "$1}'
It's also possible to embed (on Unix) the awk program in double quotes
and let the shell expand the variables
awk "/$var/{print \"Hello \"\$1}"
but this requires a lot of fiddling with escapes since in awk one uses
double quotes for strings, and you have to prevent that awk parameters
like $0 or $1 will also be expanded by the shell.
Janis


|