Declaring an awk function in bash

I have an awk script that is being called:

awk -f myawkfile.awk arguments 

awk script is called in my bash script using the same call mentioned.

Can I declare it as a function in my bash script instead of calling awk script. I thought it would be easy by writing awk in front and back ticking all the code, and then assigning a function name to the call as desired. Somehow this doesn't do the trick.

I am trying to do this because I do not want my script to depend on another script. And I'm not the one who wrote the awk script. It takes the file as input, does some, and returns the modified file that is used in my script.

+6
source share
2 answers

Using heredoc notation , you can write something like this

 #!/bin/bash awk_program=$(cat << 'EOF' /* your awk script goes here */ EOF ) # ... # run awk script awk "$awk_program" arguments # ... 
+9
source

Just write awk script in function:

 #!/bin/sh -e foo() { awk '{print $2}' " $@ "; } foo ab # Print the 2nd column from files a and b printf 'abc\nd ef\n' | foo # print 'b\ne\n' 

Note that the awk standard seems ambiguous with respect to behavior if an empty string is passed as an argument, but the shell ensures that " $@ " expands to null fields and not an empty string, so this is only a problem when calling foo with an empty an argument.

+2
source

Source: https://habr.com/ru/post/921197/


All Articles