Bash – Using bash shell function inside AWK

awkbash

Is it possible to use bash function inside AWK somehow?

Example file (string, int, int, int)

Mike 247808 247809 247810

Trying to convert values from decimal to hexadecimal.

Function defined either in .bashrc or in shell script.

$ awk '{print $1 ; d2h($2)}' file

awk: calling undefined function d2h
 input record number 1, file file
 source line number 1

Best Answer

Try to use system() function:

awk '{printf("%s ",$1); system("d2h " $2)}' file

In your case system will call d2h 247808 and then append output of this command to printf output:

Mike 3C800

EDIT:

As system uses sh instead of bash I can't find a way to access .bashrc. But you can still use functions from your current bash script:

#!/bin/bash
d2h() {
    # do some cool conversion here
    echo "$1" # or just output the first parameter
}
export -f d2h
awk '{printf("%s ",$1); system("bash -c '\''d2h "$2"'\''")}' file

EDIT 2:

I don't know why, but this is not working on my Ubuntu 16.04. This is strange, because it used to work on Ubuntu 14.04.