Home > Archive > AWK > November 2005 > Misunderstanding of short script behaviour
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Misunderstanding of short script behaviour
|
|
| Clemence Magnien 2005-11-11, 7:55 am |
| Hello,
I have used awk for a few years, up till now only to do very simple
tasks like selecting some fields in input files, or adding line numbers
to lines in a file.
A few days ago I began to use it to do more complicated things, and
have managed to do some tasks really easily. But now I'm stuck
because I don't understand why a very simple script behave like
it does.
The script is:
{
if($1 == "a")
# print $0;
word = $1;
print "word : ", word;
}
A far as I understand it, this script should consider all lines (and
only those lines) with first field equal to the string "a", and print
"word : a" for each of those lines.
But when I feed it the following file:
$ cat test2
a 1
b fd
(using the command cat test2 | awk -f fonction, where fonction
is the file where the script is written), I get the following output:
word : a
word : a
(i.e. two lines where I expected only one).
Moreover, if I uncomment the #print $0; line above, I get the
following output:
a 1
word : a
word : b
which means the additional print $0 instruction has changed
the value a variable gets assigned later...
I think I'm missing something really obvious but I can't see why.
I have read the manual, but maybe too fast, I'll go have another
look at it...
Thanks,
Clemence
| |
| Clemence Magnien 2005-11-11, 7:55 am |
|
Clemence Magnien wrote:
> Hello,
>
> I have used awk for a few years, up till now only to do very simple
> tasks like selecting some fields in input files, or adding line numbers
> to lines in a file.
> A few days ago I began to use it to do more complicated things, and
> have managed to do some tasks really easily. But now I'm stuck
> because I don't understand why a very simple script behave like
> it does.
>
> The script is:
> {
> if($1 == "a")
> # print $0;
> word = $1;
> print "word : ", word;
> }
OK I'm sorry, I've understood what the problem is.
I usually know better than to forget the { } for the body of
an "if" statement.
It was indeed something obvious.
Sorry about this,
Clemence
| |
| Ed Morton 2005-11-11, 7:55 am |
| Clemence Magnien wrote:
> Clemence Magnien wrote:
>
>
>
> OK I'm sorry, I've understood what the problem is.
> I usually know better than to forget the { } for the body of
> an "if" statement.
> It was indeed something obvious.
Actually, if that was the whole script, there shouldn't even be an "if".
It should be using awks normal condition evaluation section, e.g.:
$1 == "a" {
# print $0;
word = $1;
print "word : ", word;
}
Regards,
Ed.
|
|
|
|
|