Combining Quotes:

The Goal:

The end result is to be able to embed the shell variable in the awk command line and have the shell expand the variable without interfering with awk's field designators, $1 and $2.

Setting the Shell Variable:

name="Jacob Savage" (sh, bash and ksh)
set name = "Jacob Savage" (csh and tsh) 

The Line from the Datafile:

Jacob Savage:408-298-7732:934 La Barbara Dr. , San Jose,CA:02/27/78:500000 

The awk Command Line:

						awk -F: '$1 ~ /^'"$name"'/{print $2}' datafile
(Output)
408-298-7732
					

Step 1:

Test your knowledge of the Linux command at the command line before plugging in any shell variables.

						awk -F: '$1 ~ /^Jacob Savage/{print $2}' filename
(Output)
408-298-7732
					

Step 2:

Plug in the shell variable without changing anything else. Leave all quotes as they were.

						awk -F: '$1 ~ /^$name/{print $2}' datafile
					

Starting at the left-hand side of the awk command leave the first quote as is, and right before the shell dollar sign in $name, place another single quote. Now the first quote is matched and all text within these two quotes is protected from shell interference. The variable is exposed. Now put another single quote right after the e in $name. This starts another matched set of single quotes ending after awk's closing curly brace. Everything within this set of quotes is also protected from shell interpretation.



Step 3:

Enclose the shell variable in a set of double quotes. This allows the variable to be expanded but the value of the variable will be treated as a single string if it contains white space. The white space must be protected so that the command line is parsed properly.



Count the number of quotes. There should be an even number of single quotes and an even number of double quotes.

Example:

						oldname="Ellie Main"
newname="Eleanor Quigley"
					

  1. Make sure the command works.

    								awk -F: '/^Ellie Main/{$1="Eleanor Quigley"; print $0}' datafile
    							
  2. Plug in the variables.

    								awk -F: '/^$oldname/{$1="$newname"; print $0}' datafile
    							
  3. Play the quoting game. Starting at the first single quote at the left, move across the line until you come to the variable, $oldname, and place another single quote just before the dollar sign. Put another single quote right after the last letter in the variable name.

    Now move to the right and place another single quote right before the dollar sign in $newname. Put another single quote after the last character in $newname.



  4. Count the number of single quotes. If the number of single quotes is an even number, each quote has a matching quote. If not, you have forgotten a step.

  5. Enclose each of the shell variables in double quotes. The double quotes are placed snugly around the shell variable.



..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.68