Gil
Gil

Reputation: 1538

Declaring an awk function in bash

I have an awk script which is called by:

awk -f myawkfile.awk arguments

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

Can I, instead of calling the awk script declare it as a function in my bash script. I thought it would be easy by writing an awk in front and back ticking the whole code, then to assign a function name to call it at will. Somehow it doesnt do the trick.

I am trying to do this because I don't want my script to have dependency on another script. And I am not the one who wrote the awk script. It takes a file as input , does some stuff and gives back the modified file which is used in my script.

Upvotes: 6

Views: 2041

Answers (2)

William Pursell
William Pursell

Reputation: 212504

Just write the awk script in a function:

#!/bin/sh -e

foo() { awk '{print $2}' "$@"; }
foo a b                         # Print the 2nd column from files a and b
printf 'a b c\nd e f\n' | foo   # print 'b\ne\n'

Note that the awk standard seems ambiguous on the behavior if the empty string is passed as an argument, but the shell guarantees that "$@" expands to zero fields rather than the empty string, so it's only an issue if you invoke foo with an empty argument.

Upvotes: 3

xaizek
xaizek

Reputation: 5252

Using heredoc notation one can write something like this

#!/bin/bash

awk_program=$(cat << 'EOF'
    /* your awk script goes here */
EOF
)

# ...

# run awk script
awk "$awk_program" arguments

# ...

Upvotes: 10

Related Questions