Awk 递归文件包括

Awk 递归文件包括,awk,Awk,我正在编写一个awk脚本,以在shell脚本中递归地包含源文件: $ cat build.awk function slurp(line) { if ( line ~ /^\. / || line ~ /^source / ) { split(line, words) while ( (getline _line < words[2]) > 0 ) { slurp(_line) } } else

我正在编写一个awk脚本,以在shell脚本中递归地包含源文件:

$ cat build.awk 
function slurp(line) {
    if ( line ~ /^\. / || line ~ /^source / ) {
        split(line, words)
        while ( (getline _line < words[2]) > 0 ) {
            slurp(_line)
        }
    } else if ( NR != 1 && line ~ /^#!/ ) {
        # Ignore shebang not in the first line
    } else {
        print line
    }
}

{
    slurp($0)
}
我希望通过运行
awk-f build.awk a.sh

#!/bin/sh
echo this is a
echo this is b
echo this is c
echo this is d
然而,实际结果是

#!/bin/sh
echo this is a
echo this is b
echo this is c

d.sh不包括在内。如何解决此问题?我的错误是什么?

啊哈,那是因为在awk中,变量没有词法范围!我太不懂awk语言了。以下工作:

$ cat build.awk 
function slurp(line,    words) {
    if ( line ~ /^\. / || line ~ /^source / ) {
        split(line, words)
        while ( (getline _line < words[2]) > 0 ) {
            slurp(_line)
        }
    } else if ( NR != 1 && line ~ /^#!/ ) {
        # Ignore shebang not in the first line
    } else {
        print line
    }
}

{
    slurp($0)
}

$ awk -f build.awk a.sh 
#!/bin/sh
echo this is a
echo this is b
echo this is c
echo this is d
$cat build.awk
函数slurp(行、字){
如果(行~/^\./| |行~/^source/){
拆分(行、字)
而((getline _line0){
slurp(_线)
}
}else if(NR!=1&&line~/^#!/){
#忽略不在第一行的shebang
}否则{
打印行
}
}
{
咕噜咕噜(0美元)
}
$awk-f build.awk a.sh
#!/垃圾箱/垃圾箱
回声这是一个
我是b
我是c
这是d

啊哈,那是因为在awk中,变量没有词法范围!我太不懂awk语言了。以下工作:

$ cat build.awk 
function slurp(line,    words) {
    if ( line ~ /^\. / || line ~ /^source / ) {
        split(line, words)
        while ( (getline _line < words[2]) > 0 ) {
            slurp(_line)
        }
    } else if ( NR != 1 && line ~ /^#!/ ) {
        # Ignore shebang not in the first line
    } else {
        print line
    }
}

{
    slurp($0)
}

$ awk -f build.awk a.sh 
#!/bin/sh
echo this is a
echo this is b
echo this is c
echo this is d
$cat build.awk
函数slurp(行、字){
如果(行~/^\./| |行~/^source/){
拆分(行、字)
而((getline _line0){
slurp(_线)
}
}else if(NR!=1&&line~/^#!/){
#忽略不在第一行的shebang
}否则{
打印行
}
}
{
咕噜咕噜(0美元)
}
$awk-f build.awk a.sh
#!/垃圾箱/垃圾箱
回声这是一个
我是b
我是c
这是d