Reputation: 431
Sample function:
$ testfn() { echo "${1} world"; }
$ testfn hello
hello world
awk example:
$ echo "something bla bla2"|awk '$1 ~/something/ { print $0; }'
something bla bla2
Now I want to change "something" to "something world" using created above function, when printing it as a whole line, by passing first awk " column element" as a parameter:
$ echo "something bla bla2"|awk '$1 ~/something/ { $1="'"$(testfn) $1"'" ; print $0 }'
world bla bla2
^^ Above doesn't work
Is there any way to pass parameters from awk to the function inside awk ?
Upvotes: 0
Views: 4920
Reputation: 54392
No - you can't call shell functions from inside of awk
. It's not a shell. However, a common workaround involves adding your function to a file and calling it using awk's system()
function. Here's a simple example:
Contents of yourfunction.sh
:
{
echo "$1 world"
}
Then run:
echo "what the ..." | awk '{ system("./yourfunction.sh" FS $1) }'
Results:
what world
Note that if you find yourself having to do this, there's almost certainly a better approach. What are you actually trying to do here?
EDIT:
In response to the comments below, use the getline()
function:
echo "what the ..." | awk '{ "./yourfunction.sh" FS $1 | getline $1 }1'
Results:
what world the ...
Here's some info re the getline()
function:
http://www.gnu.org/software/gawk/manual/html_node/Getline.html
Upvotes: 1
Reputation: 203324
Highly unrecommended but:
$ cat .env
testfn() { echo "${1} world"; }
$ echo $BASH_ENV
.env
$ echo "something bla bla2" | awk '$1 ~/something/{"bash -c \"testfn " $1 "\"" | getline $1; print $0}'
something world bla bla2
Now, tell us what you're really trying to do and we can help you write a sane script to do that.
Upvotes: 2