awk中调用shell函数的步骤

awk中调用shell函数的方法

在老外的论坛上看到的:http://www.unix.com/shell-programming-scripting/49026-external-function-awk.html

 

Hi.

Here is a script that attempts various methods of calling functions:

Code:
<!-- ntstart-->#!/usr/bin/env sh

# @(#) s1       Demonstrate functions with awk.

#  ____
# /
# |   Infrastructure BEGIN

set -o nounset
echo

debug=":"
debug="echo"

## The shebang using "env" line is designed for portability. For
#  higher security, use:
#
#  #!/bin/sh -

## Use local command version for the commands in this demonstration.

echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version bash awk

my_shell_local()
{
  echo " Local function $FUNCNAME called."
}

kamel_seg()
{
  echo " Function $FUNCNAME called with arguments \"$*\"."
}

echo
echo " Function is exported to sub-shells:"
export -f kamel_seg
typeset -F

# |   Infrastructure END
# \
#  ---

echo
echo " Calling shell function from shell:"
kamel_seg hello

echo
echo " Calling shell function from awk:"
awk '
BEGIN { print " In awk" ; kamel_seg }
'

echo
echo " Calling shell function from awk system() call:"
awk '
BEGIN { print "In awk - system" ;
 system(" echo Hi from system call" ) ; system( "kamel_seg from awk" ) }
'

echo
echo " Calling awk function:"
awk '
function my_function( message )
{
  print " awk function my_function called, argument:" message
}
BEGIN { print " Calling my_function from BEGIN block."
 my_function( " Hello there." )
}
'

echo
echo " Calling awk program that calls a shell script with system():"
awk '
BEGIN { print " Calling helper." ; system( "./helper" ) }
'

exit 0<!-- ntend-->

 

<!-- width:820px; height:1282px;-->

Producing:

Code:
<!-- ntstart-->% ./s1

(Versions displayed with local utility "version")
GNU
 bash 2.05b.0
GNU
 Awk 3.1.4

 Function is exported to sub-shells:
declare -fx kamel_seg
declare -f my_shell_local

 Calling shell function from shell:
 Function kamel_seg called with arguments "hello".

 Calling shell function from awk:
 In awk

 Calling shell function from awk system() call:
In awk - system
Hi from system call
 Function kamel_seg called with arguments "from awk".

 Calling awk function:
 Calling my_function from BEGIN block.
 awk function my_function called, argument: Hello there.

 Calling awk program that calls a shell script with system():
 Calling helper.
 Script "helper" called.
 awk script called from shell script helper<!-- ntend-->

 

<!-- width:820px; height:482px;-->

Among the other points, this illustrates that shell functions can be called from awk system(), provided the shell functions are exported (frankly, I was not expecting this; I simply was trying to exhaust all the possibilities).

The brief declare output shows the difference between local and exported functions.

Best wishes ... cheers, drl