特定の文字列を含む関数の完全な関数宣言を印刷するには?

特定の文字列を含む関数の完全な関数宣言を印刷するには?

私の中には多くの関数がありますが、bashrc新しく作成した関数の場合、関数名を忘れてしまうことが多いです。

たとえば、私の関数に次の関数を定義すると、次のようになります.bashrc

function gitignore-unstaged
{
    ### Description:
    # creates a gitignore file with every file currently not staged/commited.
    # (except the gitingore file itself)
    ### Args: -

    git ls-files --others | grep --invert-match '.gitignore' > ./.gitignore

}

関数の定義を印刷する他の関数が必要です。たとえば、次のようになります。

$ grepfunctions "gitignore"
function gitignore-unstaged
{
    ### Description:
    # creates a gitignore file with every file currently not staged/commited.
    # (except the gitingore file itself)
    ### Args: -

    git ls-files --others | grep --invert-match '.gitignore' > ./.gitignore
}

しかし、「gitignore」と一致したくありません。すべてfuntctionとの間に文字列が}あるので$ grepfunctions "###"、とは$ grepfunctions "creates"まったく同じ内容を出力する必要があります。これも理由だ、なぜ?-f などを宣言しても問題は解決しません。

私が試したこと

  • 利用できませんgrep
  • 私はこれがsed -n -e '/gitignore-unstaged/,/^}/p' ~/.bashrc私が望むものを印刷することを知っていますが、sed -n -e '/creates/,/^}/p' ~/.bashrcそうではありません。代わりに、私は以下を受け取ります:

        # creates a gitignore file with every file currently not staged/commited.
        # (except the gitingore file itself)
        ### Args: -
    
        git ls-files --others | grep --invert-match '.gitignore' > ./.gitignore
    }
    

    関数名と最初の名前が{削除されますが、これは私が望むものではありません。

特定の文字列を含む関数の完全な関数宣言を印刷するには?もちろん、sedに加えて他のツールも許可されています。

ベストアンサー1

を使用すると、zsh次のことができます。

 printf '%s() {\n%s\n}\n\n' ${(kv)functions[(R)*gitignore*]}

現在定義されている関数から情報を取得します(コメントは除く)。

ソースファイルから情報を抽出したい場合は、完全なシェルパーサーを実装しないと確実に実行できません。

関数宣言方法についていくつかの仮定ができる場合(たとえば、常に行の先頭にkshスタイル関数定義を使用している場合)、次のことができますfunction}

perl -l -0777 -ne 'for (/^function .*?^\}$/gms) {
  print if /gitignore/}' ~/.bashrc

または、関数の本文を見てください。

perl -l -0777 -ne 'for (/^function .*?^\}$/gms) {
  print if /\{.*gitignore/s}' ~/.bashrc

おすすめ記事