Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to define a user-defined function inside an awk statement which is inside a bash script?

I think the question speaks for itself. I am a beginner so please let me know if this is possible or not. If not, came you give me a better solution because my bash script depends heavily on certain awk statements but the majority of the script is in bash. I am comparing two files using an awk statement in my bash script. Basically checking if the values are the same or not. (see the files below)

file1.txt

Name  Col1  Col2  Col3 
-----------------------
row1  1     4     7         
row2  2     5     8          
row3  3     6     9

file2.txt

Name  Col1  Col2  Col3   
-----------------------         
row1  1     4     7 
row2  2     5     999

Here is the structure of my bash script:

#!/bin/bash
.
.
.

awk -F '\t' '
              # skips first two lines
              FNR < 2 {next}                       
              FNR == NR {           
                for (i = 2; i <= NF; i++) {
                  a[i,$1] = $i;      
                }    
                b[$1];           
                next;       
              }

              ($1 in b) {                          

                for (i = 2; i <= NF; i++) 
                {
                   # does something
                }
              }
' file1.txt file2.txt
.
.
.

I have a lot of repetitive code that are only useful in the awk statements and so I want to create a function that would be placed in the awk statement to avoid repetition. Is this possible?

Let me know if further explanation is required.

like image 763
Redson Avatar asked Dec 05 '22 06:12

Redson


1 Answers

Sure, just define functions:

awk '
function foo() {
   print "Hello World"
}
BEGIN {
    foo()
    foo()
}
'
like image 127
Ed Morton Avatar answered Jun 01 '23 13:06

Ed Morton