Search code examples
awkgnuopenvms

AWK - error in script with count variable OR error in AWK Implementation / version?


  • Awk version: GNU Awk 3.1.1
  • Platform: OpenVMS 8.4-L1
  • Awk knowledge: limited

Script (Awk one liner). NOTE: OpenVMS parameter parsing requires quotes

gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

I wanted the following instead

file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

If I change the awk command above to: ...{x = -1}... I get

**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3

What I am wondering is

  1. Can someone else using a different platform test this to see if it produces the same output?
  2. Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)


Solution

  • You need to use ++x in place of x++. The x++ initially evaluates to 0 (but increments x to 1), and 0 is false, so the action is not taken; nothing is printed for the first line.

    When you initialize x to -1, the first line is printed because x++ evaluates to -1 which is true; the second is skipped because x is 0, etc.

    You don't need the BEGIN block. Variables are auto-vivified with zero (or the empty string) as the value. And in fact you don't need to trigger the printing based on whether x is zero or not; you simply want to always print an incremented value of x.

    So, on a Mac (Unix-like) system, I can run:

    $ gawk "-F" ";" '{print $0,$1";"++x}' file.in
    file.log;2000 file.log;1
    file.log;1999 file.log;2
    file.log;1998 file.log;3
    file.log;1997 file.log;4
    $
    

    Translated to VMS conventions, that would be:

    gawk "-F" ";" "{print $0,$1"";""++x}" file.in