【问题标题】:awk script doesn't working correctly with gsub $10awk 脚本无法与 gsub 一起正常工作 $10
【发布时间】:2018-05-14 02:45:16
【问题描述】:

我有很多套用信需要生成。

    $>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
               }
       }

--我打过电话

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

--10 我想变成这样

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

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

--20 但我明白了

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

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

上面的$10不正确,变成$1加0,我尝试双引号和 单引号,它也不起作用。

AND 11 美元变成 1 美元加 1。

我的 awk 是 4.1.3,我更新到最新版本也无法正常工作。

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

我的脚本出了什么问题?我怎样才能让它工作?

【问题讨论】:

标签: linux awk gsub


【解决方案1】:

将内部 for 循环更改为

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

在您的情况下,$1$10 有机会匹配之前得到匹配。

【讨论】:

    【解决方案2】:

    要使输出字段与输入字段的显示顺序相同:

      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
    

    【讨论】:

    • 抱歉,无法在评论中使用 Markdown 格式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    相关资源
    最近更新 更多