shellawkscriptingtcsh

multiline awk script inside shell script


#!/usr/bin/tcsh

 cmd='BEGIN{c=0}{
      if($1=="Net"){print $0}

       if($1=="v14")
       {
         if($4>=200)
           {print "Drop more than 200 at "$1}
          }

              }'

         
awk -f "$cmd" input_file.txt > output_file.txt

I am trying to execute shell script which contains multiline awk script inside it. storing awk script (especially multiline awk script) to a variable cmd & then excuting that cmd in awk -f "$cmd" input_file.txt > output_file.txt.

this is giving an error like below

     awk: fatal: can't open source file `BEGIN{c=0}{
          if($1=="Net"){print $0}

           if($1=="v14")
           {
             if($4>=200)
              {print"Drop more than 200 at $1}
               }

                }' for reading (No such file or directory)

my questin is how do i execute shell script which contains multiline awk script inside it? can you please help me with this as i couldn't figureout even after searching in google/reference manual?


Solution

    1. Don't write [t]csh scripts, see any of the many results of https://www.google.com/search?q=csh+why+not, use a Bourne-derived shell like bash.
    2. Don't store an awk script in a shell variable and then ask awk to interpret the contents of that variable, just store the script in a function and call that.

    So, do something like this:

    #!/usr/bin/env bash
    
    foo() {
        awk '
            { print "whatever", $0 }
        ' "${@:--}"
    }
    
    foo input_file.txt > output_file.txt