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
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 :-)
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