Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!linus!philabs!cmcl2!seismo!rochester!rocksanne!sunybcs!neil From: neil@sunybcs.UUCP (Neil Smithline) Newsgroups: net.unix Subject: Re: passing command line arguments to awk Message-ID: <27@sunybcs.UUCP> Date: Sun, 1-Jun-86 21:18:05 EDT Article-I.D.: sunybcs.27 Posted: Sun Jun 1 21:18:05 1986 Date-Received: Tue, 3-Jun-86 23:48:48 EDT References: <198@comp.lancs.ac.uk> <1261@utcs.uucp> Reply-To: neil@gort.UUCP (Neil Smithline) Distribution: net Organization: SUNY/Buffalo Computer Science Lines: 35 Keywords: awk In article <1261@utcs.uucp> onn@utcs.UUCP (Brian Onn) writes: >In article <198@comp.lancs.ac.uk> craig@comp.lancs.ac.uk (Craig Wylie) writes: >> >>I surrender -- is it possible to pass command line arguments to awk? >> >>If so - how. While I'm at it how about doing the same thing to sed. >> >> >>Craig. > >The only way I know of to pass command line arguments into awk is by >defining them as variables in an assign statement on the awk command line, ie > >awk -f awkfile arg1=$1 arg2=$2 inputfile > >will assign $1 to arg1, and $2 to arg2, inside the body of the awk program. It >is not possible to assign variable values in this manner to variables that >are used inside an action associated with the BEGIN pattern. There is a much more general method to use. If you put the awk code inside of the shell script (rather than using the 'awk -f' option) it can be done as follows: ----------------------------------------------------------------------------- #!/bin/csh -f awk ' {awkvar = '$1'; printf("awkvar: %s, shellvar: %s\n",awkvar,'$1')}' ----------------------------------------------------------------------------- This program will wait for you to enter a line of input (awk always waits for this - it is not essential for the program to work - just for awk to work), and then print out the first argument to the shell twice. The way that this is done is by closing the single quotes (') every time you want to access a shell variable and then reopening them afterwards. In the above script the "$1" refers to the first argument to the shell and not to the first word of the input line. This can be done the same way for sed (or any other program for that matter) because it is not making use of any features of awk but rather those of the shell - Neil