你好 awk ninjas 我需要一些幫助,所以我找到了一個解決方案,可以從這里從我的 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
先感謝您。
uj5u.com熱心網友回復:
將每個替換#為::
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 內置的目的是什么?了解更多資訊。
uj5u.com熱心網友回復:
寫作作為答案以獲得更好的格式化功能。 您可以嘗試使用自定義的“虛擬”變數并在其中存盤注釋。
讓我們宣告我們的函式:
test_function () {
__COMMENT="TEST_FUNCTION"
}
我使用__COMMENT變數作為我們的占位符。請注意,這bash將在 2 行中列印函式名稱和變數,因此我們必須在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 個字符(引號)。
uj5u.com熱心網友回復:
嘗試通過此管道發送您的輸出:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397184.html
