Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 988
Gil Avatar asked Jul 24 '12 11:07

Gil


People also ask

Can I use awk in bash?

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.

How do you write a function in awk?

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.

What is awk command in bash?

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.

What is awk '{ print $1 }'?

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.


2 Answers

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

# ...
like image 125
xaizek Avatar answered Sep 18 '22 02:09

xaizek


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.

like image 42
William Pursell Avatar answered Sep 20 '22 02:09

William Pursell