특정 문자열을 포함하는 함수의 전체 함수 선언을 인쇄하는 방법은 무엇입니까?

특정 문자열을 포함하는 함수의 전체 함수 선언을 인쇄하는 방법은 무엇입니까?

내 안에는 많은 함수가 있는데 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

관련 정보