passing command line arguments to awk

John M. Ritter jmr at motown.UUCP
Fri May 30 22:35:38 AEST 1986


> 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.

Well, I know the feeling. A few months ago I was presented with this same
situation and it drove me crazy. It's really fairly simple. I've posted an
answer as I know several people have come across this.

I've included a section of code from an awk script that pulls stuff from the
environment. No real changes to make the variables command line arguments.
The script also shows another problem I had - how to imbed control codes
for "fun stuff". I had to find a way to avoid sticking a true \033 in the
middle of the script.

As for sed, I just do something like this:

FIND="search"
CHANGE="new string"
echo "We'll search for some stuff and send it to sed." |
sed -e s/$FIND/"$CHANGE"/

Hope this helps!
------------------------------------------------------------------------------
"I enjoy working with human beings, and                         John M. Ritter
have stimulating relationships with them."                  Allied-Signal Inc.
                            - HAL 9000                Corporate Tax Department
                      {bellcore,harpo,ihnp4,infopro,princeton,sys1}!motown!jmr
------------------------------------------------------------------------------

# Simple awk script to receive passing parameters
PHRASE1="Hello_world."
PHRASE2="Hello world."

echo " " |
awk '
BEGIN {
# Have to put environment stuff "outside" of awk
	TERM = "'$TERM'"		# From Environment
	PHRASE1 = "'$PHRASE1'"		# From Environment
# Note weird quotes. Have to pass as one variable.
# If quoting structure was the same as above - disaster:
	PHRASE2 = "'"$PHRASE2"'"	# From Environment

	ESC = 27
	if (TERM == "wy75") {
		REVERSE_ON  = sprintf("%c%s", ESC, "[7m")
		REVERSE_OFF = sprintf("%c%s", ESC, "[m")
	}
	if (TERM == "adds25") {
		REVERSE_ON  = sprintf("%c%s", ESC, "G4")
		REVERSE_OFF = sprintf("%c%s", ESC, "G0")
	}
} # End of BEGIN

{ print REVERSE_ON PHRASE1 REVERSE_OFF
  print REVERSE_ON PHRASE2 REVERSE_OFF}'



More information about the Comp.unix mailing list