variable as search-pattern: if ($0 ~ myVar) 
Author Message
 variable as search-pattern: if ($0 ~ myVar)

Hello,

how can I search a pattern that is given in an
environment-Variable?

BEGIN {
  SEARCH_= ENVIRON["SEAR"];

Quote:
}

{

  if ($0==SEARCH_ ) {   # works if identical
      ...

Quote:
}

But how can I search SEARCH_ within $0 or at the beginning
like
    if ($0 ~ /Hello/) { ...
or
    if ($0 ~ /^Hello/) {

??

thx
Ekkard



Wed, 07 Jan 2004 04:04:50 GMT  
 variable as search-pattern: if ($0 ~ myVar)

Quote:

> how can I search a pattern that is given in an
> environment-Variable?

> BEGIN {
>  SEARCH_= ENVIRON["SEAR"];
> }

Yes. But note that "SEAR" has to be an environment variable, a shell
variable is not enough (like any other process, awk can't see pure shell
variables).

  SEAR="find this!"
  export SEAR
  awk ...

for Bourne shells or

  export SEAR="find this!"
  awk ...

for the newer Bourne/POSIX shell derivatives (ksh, bash, zsh).
If you emit the "export", it's a pure shell variable that is visible only
to the shell.

For one command, you can also use

  SEAR="find this!" awk ...

Or use awk's -v flag:

  awk -v SEARCH_="$SEAR" ...

(on Solaris, use nawk, gawk or mawk. The old awk on Solaris doesn't have
the -v option (but of course, it doesn't have ENVIRON[] neither)).

Quote:
> {

>  if ($0==SEARCH_ ) {   # works if identical
>      ...
> }

> But how can I search SEARCH_ within $0 or at the beginning

The solution in the subject is correct; it must be something else that
is wrong.

Regards...
                Michael



Wed, 07 Jan 2004 06:21:55 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Parameter MyVar = ## Vs Parameter ( MyVar = ## )

2. Appending to $0 or $_

3. executable awk scripts and shell var $(basename $0)

4. Newbie Help required: Deleting double entries in a line ($0)

5. !x[$0]++

6. mechanism of application ($0 or the line)

7. $0 == false ??

8. program name -> perl's $0

9. $0 == __FILE__ idiom for Unix only?

10. ruby 1.6.5, irb $0

11. __FILE__ == $0 refactored in Ruby?

12. Replacement for __FILE__ == $0

 

 
Powered by phpBB® Forum Software