Pass the variable to awk with awk's -v
option. e.g. to set the awk variable n
to the same value as the csh variable $variable
:
% set variable=2
% awk -v n="$variable" '{print $n}' random
B
B
B
Alternatively, pass the variable assignment as an argument after the script (awk will interpret arguments like x=y
as an assignment, not as a filename):
% set variable=4
% awk '{print $n}' n="$variable" random
D
D
D
In both cases, the awk script will interpret $n
as "the field numbered n"
Alternatively, you can use environment variables. awk can access them through the ENVIRON
array. e.g.
% setenv variable 2
% awk '{print $ENVIRON["variable"]}' random
B
B
B
BTW, as others have mentioned in comments, csh
/tcsh
is not a good choice for a scripting language - use a bourne-like shell for shell scripting. tcsh
is still kind of OK-ish for an interactive shell, but doesn't offer anything that other shells don't already offer - csh was a superior interactive shell in the 1980s but other shells have long since surpassed it (and csh has the disadvantage of being different from a good scripting shell language, so you won't get experience with scripting just from interactive use of it). Try switching to bash, ksh, or zsh instead.
tcsh
andcsh
are terrible for shell scripting. There are many inconsistencies that cannot really be coded around. I would most strongly recommend that you write scripts inbash
orsh
rather than[t]csh
. (By all means leave your interactive sessions withtcsh
.) – Chris Davies Dec 17 '21 at 09:22