简体   繁体   中英

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.

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

# ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM