Michael
Michael

Reputation: 5

awk script doesn't working correctly with gsub $10

I have a lot of form letter need generate.

    $>cat debug-form-letter
    The first field is $1, the second $2, the third $3,
    the 10th field is $10,but  the 10th correct value  is varA.


    $> cat debug-replace-value
    var1|var2|var3|var4|var5|var6|var7|var8|var9|varA|varB

    $> cat debug-replace-form-letter.awk
    BEGIN {FS = "|"
                       while (getline <"debug-form-letter")
                       line[++n] = $0
       }
    {for (i = 1; i <= n; i++) {  
                       s = line[i]         
                       for (j = 1; j <= NF; j++)  
                                  gsub("\\$"j, $j, s)
                       print s
               }
       }

--I called

    $> awk -f debug-replace-form-letter.awk debug-replace-value 

--10 I want to get like this

    The first field is var1, the second var2, the third var3,

    the 10th field is varA,but  the 10th correct value  is varA.

--20 but I get this

    The first field is var1, the second var2, the third var3,

    the 10th field is var10,but  the 10th correct value  is varA.

the above $10 is not correct ,it is become $1 plus 0,I try to double quote and single quote ,it's not working too.

AND $11 is become $1 plus 1.

my awk is 4.1.3 ,and I update to the latest version it's not working too.

    $> awk -V
    GNU Awk 4.1.3, API: 1.1
    Copyright (C) 1989, 1991-2015 Free Software Foundation.

what's wrong with my script?how can I make it working?

Upvotes: 0

Views: 457

Answers (2)

Bilbo
Bilbo

Reputation: 380

To make the output fields appear in the same order as the input fields:

  for( FldNum = NF;  FldNum >= 1; FldNum-- ) { # scan all field positions from last to first
    print $(    NF - FldNum +  1 )             # emit the field at the reverse-order position, except field-zero
    if(              FldNum >  1 ) print "\t"  # emit Tab after each field, but not after the last field to be printed
  }                                            # done scanning fields
  print "\n"                                   # emit EOL after every line

Upvotes: 0

Anthony Geoghegan
Anthony Geoghegan

Reputation: 11993

Change the inner for loop to

for (j = NF; j >= 1; j--)

In your case, $1 gets matched before $10 has a chance to match.

Upvotes: 1

Related Questions