如何获取awk打印函数的名称和注释



你好,awk忍者,我需要一些帮助,所以我找到了一个从这里打印shell脚本中定义的函数名的解决方案,但我的问题是,我希望我的函数能显示注释。。。下面是一个如何定义我的函数的例子。

function1() { # this is a function 1
command1
}
function2() { # this is a function 2
command2
}
function3() { # this is a function 3
command3
}

因此,提供的有效命令是这样的:typeset -f | awk '/ () $/ && !/^main / {print $1}',输出将是这样:

function1
function2
function3

但我希望输出是这样的(函数名和注释之间有4个空格也很好(:

function1    # this is a function 1
function2    # this is a function 2
function3    # this is a function 3

提前谢谢。

::替换每个#

function1() { : this is a function 1
command1
}
function2() { : this is a function 2
command2
}
function3() { : this is a function 3
command3
}

$ typeset -f | awk '/ () $/{fn=$1} /^ *:/{ print fn $0 }'
function1    : this is a function 1;
function2    : this is a function 2;
function3    : this is a function 3;

根据您的喜好更改awk脚本,以匹配您拥有的任何其他函数布局和/或根据您的意愿调整输出。

请参阅:(冒号(GNU Bash内置程序的用途是什么?了解更多信息。

作为一种答案写作,以获得更好的格式化功能您可以尝试使用自定义,";伪";变量并在其中存储注释。

让我们声明我们的函数:

test_function () {
__COMMENT="TEST_FUNCTION"
}

我使用__COMMENT变量作为占位符。注意,bash将在两行中打印函数名和变量,因此我们必须在awk代码中使用状态机:

typeset -f | awk 
'match($0, /__COMMENT="[^"]*/) {
if (functionname) {
print functionname ": " substr($0, RSTART+11, RLENGTH-11)
}
}
/ () {$/ && !/^main / {functionname=$1}'

从最后开始:

/ () {$/ && !/^main / {functionname=$1}

我不得不修改你的模式以匹配我的输出,所以你可能需要删除大括号字符才能在你这边工作它将查找一个函数声明,并将其名称存储为functionname

'match($0, /__COMMENT="[^"]*/) {

它将查找我们的变量。注意,__COMMENT="的长度是11。我们需要它。

if (functionname) {
print functionname ": " substr($0, RSTART+11, RLENGTH-11)
}

如果设置了functionname,它将打印名称和匹配的子字符串,从开始跳过11个字符,从结束跳过1个字符(引号(。

尝试通过以下管道发送输出:

grep '() ' | grep -v '^main' | sed '/() { /s//    /'

说明:第一个grep查找包含具有()的函数定义的所有行。第二个过滤掉了main()函数。最后,sed命令将字符串() {替换为四个空格。

出于测试目的,我将您上面描述的输入放入一个文件s.txt中,该文件包含:

function1() { # this is a function 1
command1
}
function2() { # this is a function 2
command2
}
function3() { # this is a function 3
command3
}
main() { # this is the main function
commands
}

当我运行时

cat s.txt | grep '() ' | grep -v '^main' | sed '/() { /s//    /'

我得到这个输出:

function1    # this is a function 1
function2    # this is a function 2
function3    # this is a function 3

最新更新