简体   繁体   English

在bash中声明awk函数

[英]Declaring an awk function in bash

I have an awk script which is called by: 我有一个awk脚本,它被调用:

awk -f myawkfile.awk arguments

The awk script is called into my bash script using the same mentioned call. 使用相同的提到的调用将awk脚本调用到我的bash脚本中。

Can I, instead of calling the awk script declare it as a function in my bash script. 我可以而不是调用awk脚本将其声明为我的bash脚本中的函数。 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. 我认为通过在前面和后面写一个awk来勾选整个代码然后分配一个函数名来随意调用它会很容易。 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. 我不是那个写awk脚本的人。 It takes a file as input , does some stuff and gives back the modified file which is used in my script. 它需要一个文件作为输入,做一些东西并返回我脚本中使用的修改过的文件。

Using heredoc notation one can write something like this 使用heredoc表示法可以写出这样的东西

#!/bin/bash

awk_program=$(cat << 'EOF'
    /* your awk script goes here */
EOF
)

# ...

# run awk script
awk "$awk_program" arguments

# ...

Just write the awk script in a function: 只需在函数中编写awk脚本:

#!/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. 请注意,如果将空字符串作为参数传递,则awk标准在行为上似乎不明确,但shell保证"$@"扩展为零字段而不是空字符串,因此如果您使用以下方法调用foo ,则只会出现问题空论点。

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

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