SUMMARY: awk - command line works / script doesn't

From: Rob Ouellette <rouellet_at_ebmail.gdeb.com>
Date: Fri Apr 28 2006 - 16:44:20 EDT
Answer:  awk "/$srcStr/{$lines}" $file

Original posting is shown below.

Michael Maciolek and Matthew Stier had similar answers.

Michael Maciolek Explanation:

You're overdoing the string escapes.  When you enter a command line
such as:

> awk  '/Packing database/{print;getline;print;getline}'  CMutil

your shell removes the single quotes and hands the entire quoted
string to 'awk' as argv[1].

The same quote-removal happens in:

> awk  /"Packing database"/'{print;getline;print;getline}'  CMutil

and awk gets exactly the same string handed to it in argv[1].

Within a shell script, you need to be careful not to use single
quotes around a shell variable, but otherwise you can use the
same level of quoting to do what you need.  In this case, you
can simply script the following:

                 awk "/$srcStr/{$lines}" $file

and it'll work fine (assuming $srcStr and $lines are valid).


Thanks to all that replied!
-r

----- Forwarded by Rob Ouellette/EB/GDYN on 04/28/2006 04:32 PM -----

Rob Ouellette/EB/GDYN 
04/28/2006 03:13 PM

To
sunmanagers@sunmanagers.org
cc

Subject
awk - command line works / script doesn't





Hello All,

I wanted a simple script to search for a key word in a file and print some 
number of lines after it.  The following example works on the command line 
but not in the script shown below.  The error is "syntax error near line 
1".

I know this can be done easily in Perl. However, I'm trying to expand my 
bourne and awk shell skills...

Also, the translation of the awk command from the script, when run with 
the "-x" option, can be pasted onto the command line and run 
successfully...

Any ideas on how to make this work? 

Commands that work from the command line:
# look for "Packing database" , print that line, get and print the 
following two lines from the file CMutil
awk  '/Packing database/{print;getline;print;getline}'  CMutil
awk  /"Packing database"/'{print;getline;print;getline}'  CMutil


Script:
#!/bin/sh -x
#search string/token/word(s)
srcStr=$1
#number of lines to print after search word is found
nLines=$2
#files to search
file=$3

cnt=0
lines="print;"

while [ $cnt -lt $nLines ]
do
   lines=$lines'getline;print;'
   cnt=`expr $cnt + 1`
done

#Doesn't work
awk "'/$srcStr/{$lines}'" $file

#This doesn't work either
awk /\"$srcStr\"/"'{$lines}'" $file


Sample text (CMutil file):
Packing database blah blah blah
Date blah blah 
Database blah blah blah dump complete
_______________________________________________
sunmanagers mailing list
sunmanagers@sunmanagers.org
http://www.sunmanagers.org/mailman/listinfo/sunmanagers
Received on Fri Apr 28 16:44:56 2006

This archive was generated by hypermail 2.1.8 : Thu Mar 03 2016 - 06:43:57 EST