Results 1 to 4 of 4

Thread: How to grep a bash function

  1. #1
    Join Date
    Jul 2013
    Beans
    109

    How to grep a bash function

    Suppose I have a file containing

    Code:
    REST1
    
    function myfunction(){
    
    body of the function
    
    }
    
    REST2
    I 'd like to grep only (given the name myfunction)

    Code:
    function myfunction(){
    
    body of the function
    
    }
    Thank you

  2. #2
    Join Date
    Apr 2012
    Beans
    5,900

    Re: How to grep a bash function

    If there are no other right braces before the closing brace of the function, you could awk or sed it

    Code:
    awk '/myfunction/,/}/ {print}' myfile
    Code:
    sed '/myfunction()/,/}/!d' myfile
    If there *are* other braces, then afaik you'd need a true syntax-aware parser

  3. #3
    Join Date
    Sep 2006
    Beans
    7,953
    Distro
    Lubuntu Development Release

    Re: How to grep a bash function

    Quote Originally Posted by steeldriver View Post
    If there are no other right braces before the closing brace of the function, you could awk or sed it

    Code:
    awk '/myfunction/,/}/ {print}' myfile
    That's listed in awk but not really explained. Thanks for showing it.

    One further refinement might be to only look for the string when it is at the start of a line. Otherwise, you risk printing calls to the function rather than just the function alone.

    Code:
    awk '/^myfunction/,/}/ {print}' myfile
    The Truth Shall Make Ye Fret.

  4. #4
    Join Date
    Nov 2011
    Location
    /dev/root
    Beans
    Hidden!

    Re: How to grep a bash function

    You can also use csplit. See the info page

    Code:
    info csplit
    for example

    Code:
    csplit file.bash '/^function/' '{*}'

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •