[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Is there a way to assign to $0 in command line?

From: Peng Yu
Subject: Is there a way to assign to $0 in command line?
Date: Thu, 8 Jul 2021 19:01:36 -0500


$ seq 3 | awk -v '$0=abc' -e 'BEGIN { print } { print }'
awk: fatal: `$0' is not a legal variable name

It seems that it is impossible to assign some value to $0 in the command line.

$ { echo abc; seq 3; } | awk -e 'BEGIN { getline } BEGIN { print }  { print }'

The best walkaround that I came up is the above. But it is a little
cumbersome, as the content to be assigned to $0 has to be merged with
the stdin stream. The advantage is that the part of the code `BEGIN {
print }  { print }` does not have to change, which can be a good thing
when that part of the code should not be changed.

$ seq 3 | awk -v line=abc  -e 'BEGIN { print line } { print }'

Alternatively, I can assign it to a different variable name. But the
part of the code of `BEGIN { print }  { print }` has to be modified.
It is not preferred in certain cases.

Therefore, is there a way to directly modify $0 in the command of awk
(e.g., via -v)? Or would it make sense to allow $0 be modified in the
command (similar to the effect of changing $0 in a BEGIN block, but a
command-line way makes string escaping unnecessary.).


reply via email to

[Prev in Thread] Current Thread [Next in Thread]