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.
AWK is a programming language that is designed for processing text-based data, either in files or data streams, or using shell pipes. In other words you can combine awk with shell scripts or directly use at a shell prompt. This pages shows how to use awk in your bash shell scripts.
Function name should begin with a letter and the rest of the characters can be any combination of numbers, alphabetic characters, or underscore. AWK's reserve words cannot be used as function names. Functions can accept multiple arguments separated by comma. Arguments are not mandatory.
The awk command is a Linux tool and programming language that allows users to process and manipulate data and produce formatted reports. The tool supports various operations for advanced text processing and facilitates expressing complex data selections.
awk treats tab or whitespace for file separator by default. Awk actually uses some variables for each data field found. $0 for whole line. $1 for first field. $2 for second field.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With