How to use multiple passes with gawk?

I am trying to use GAWK from CYGWIN to process a csv file. Pass 1 finds the maximum value, and pass 2 prints records corresponding to the maximum value. I am using the .awk file as input. When I use text in a manual, it matches both passages. I can use the IF form as a workaround, but it forces me to use IF inside every pattern match, which is kind of a pain. Any idea what I'm doing wrong?

Here is my .awk file:

pass == 1
{
    print "pass1 is", pass;  
}    

pass == 2
{
if(pass == 2)
    print "pass2 is", pass;  
}    

Here is my output (the input file is just “hi”):

hello
pass1 is 1
pass1 is 2
hello
pass2 is 2

Here is my command line:

gawk -F , -f test.awk pass=1 x.txt pass=2 x.txt

I would appreciate any help.

+4
source share
3 answers

(g) awk :

awk 'FNR == NR{print "1st pass"; next}
     {print "second pass"}' x.txt x.txt

( awk gawk).
, x.txt, , , ( - , . ):

awk -F"," 'FNR==NR {max = ( (FNR==1) || ($1 > max) ? $1 : max ); next}
           $1==max'  x.txt x.txt

x.txt:

6,5
2,6
5,7
6,9

6,5
6,9

? NR , FNR reset 1 . FNR==NR .

+5

... . , . NR==FNR - , .

, . (, , USB-, , DAT- ..)

awk -F, '$1>m{delete l;n=0;m=$1}m==$1{l[++n]=$0}END{for(i=1;i<=n;i++)print l[i]}' inputfile

, :

BEGIN {
  FS=","
}

$1 > max {
  delete list           # empty the array
  n=0                   # reset the array counter
  max=$1                # set a new max
}

max==$1 {
  list[++n]=$0          # record the line in our array
}

END {
  for(i=1;i<=n;i++) {   # print the array in order of found lines.
    print list[i]
  }
}

, F.Knorr, .

, . , , , , .

( ), , , , , IO.

+3

The problem is that newlines are awk.

# This does what I should have done: 
pass==1 {print "pass1 is", pass;} 
pass==2 {if (pass==2) print "pass2 is", pass;}

# This is the code in my question:
# When pass == 1, do nothing
pass==1 
# On every condition, do this
    {print "pass1 is", pass;} 
# When pass == 2, do nothing
pass==2 
# On every condition, do this
    {if (pass==2) print "pass2 is", pass;}

Using pass == 1, pass == 2 is not so elegant, but it works.

0
source

Source: https://habr.com/ru/post/1619074/


All Articles