简体   繁体   English

我可以在awk中导入/使用bash函数吗?

[英]Can I import/use a bash function in awk?

I have a fairly large bash function library that I use in an application. 我有一个相当大的bash函数库,可以在应用程序中使用。 The library gets imported as an environment file. 该库将作为环境文件导入。 Since the functions are exported, I can use these functions in other bash scripts without any issues. 由于函数已导出,因此我可以在其他bash脚本中使用这些函数,而不会出现任何问题。

However I have another issue where I need to use an awk scriptlet and I want to be able to use a couple of functions from the bash library if possible. 但是,还有另一个问题,我需要使用awk scriptlet,并且希望尽可能使用bash库中的几个函数。

So in short I want to be able to do one of the two things: 简而言之,我希望能够执行以下两项操作之一:

  1. Use the function in the bash environment file in awk 在awk的bash环境文件中使用该功能
  2. Import bash environment file inside awk script and use any variables and/or functions that are exported using that environment file. 在awk脚本中导入bash环境文件,并使用使用该环境文件导出的任何变量和/或函数。

Works: 作品:

[root@test@Test1001 scripts]# . mfg.env
[root@test@Test1001 scripts]# set -o posix;OSMAJVER=12 EVMAJVER=11 EVMINVER=1 SYSTEM_ARCH=SSA HOST=test;check_flag RAD
[root@test@Test1001 scripts]# echo $?
0

Doesn't work: 不起作用:

[root@test@Test1001 scripts]# . mfg.env
[root@test@Test1001 scripts]# awk -v st=ssa -v 'env=OSMAJVER=12 EVMAJVER=11 EVMINVER=1 SYSTEM_ARCH=SSA HOST=test' -f /tmp/s1.awk /tmp/template.mf
bash: check_flag: No such file or directory 127

s1.awk s1.awk

BEGIN {
  FS=":"
  if (system("set -o posix;"env)!=0) {
    print "***ERROR - ENV string not valid to shell - cannot continue"
    exit 1
  }
}

/^[[:space:]]*#/{next}
/^[[:space:]]*$/{next}

{
  # field 3 processing
  n_a=split($3,a_st,",")
  # field 4 re-glue around ":" if required
  cmd=$4
  for (i=5; i<=NF; i++) cmd=cmd":"$i
  if (cmd) cmd="set -o posix;"env";"cmd
  f=0;for (i=1; i<=n_a && !f; i++) if (a_st[i]==st) f=1
  print "CMD: "cmd
  if ($3=="" || $3=="*" || f)
  system(cmd)
}

mf file: MF文件:

text:S3:rcs,ssa:check_flag RAD

I want to be able to process the above line only if the "check_flag RAD" returns true. 我希望仅在“ check_flag RAD”返回true时才能处理上述行。

No, you cannot. 你不能。

You can use export -f to export the function from your parent shell, and then run another instance of bash from awk as a child process. 可以使用export -f从父shell导出函数,然后从awk运行另一个bash实例作为子进程。 However, this is near the very height of hackery; 但是,这正接近黑客的高度。 given more details on what you actually intend to accomplish, we could almost certainly find a better-practice approach. 如果您提供了您实际打算完成的工作的更多详细信息,我们几乎可以肯定会找到一种更好的做法。

A better-practice approach is to structure your awk script to write a stream which your shell-native code can read from and operate over -- see BashFAQ #1 for best-practices around reading from an input stream field-by-field. 更好的做法是构造awk脚本,以编写一个流,您的shell本机代码可以读取该流并对其进行操作-有关字段读取输入流的最佳实践,请参见BashFAQ#1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM