Home > front end >  multiline awk script inside shell script
multiline awk script inside shell script

Time:09-17

#!/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?

CodePudding user response:

You use awk -f when you want to pass a file name for the script to execute.

Here your awk script is an inline string, so just removing the -f option will fix your issue.

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

CodePudding user response:

This is the equivalent script

$1=="Net"
$1=="v14" && $4>=200 {print "Drop more than 200 at "$1}

save into a file, for example test.awk and run as

$ awk -f test.awk input_file > output_file

Or, as for simple one time scripts you can just

$ awk '$1=="Net"; $1=="v14" && $4>=200 {print "Drop more than 200 at "$1}' input_file > output_file

obviously the above line can be inserted in a shell script as well.

  • Related