1

I have a file with more than 20-30 functions like below:

abc(){
 # code of abc function
}
efg(){
 # code of efg function
}
hij(){
 # code of efg function
}

I want to use grep/sed or any other text manipulation tools to extract the code present in a particular function.


I tried this: sed -n '/efg/,/\}/p' file.txt

Output:

efg(){
     # code of efg function
}

How do I exclude the first and last line of the output to get the code only. I know it can be removed using sed but I'd prefer it is in the one-liner itself, but can't figure it out myself

4
  • What if the function is all on one line? Commented Jul 11, 2018 at 7:43
  • you might want to check an awk solution here. stackoverflow.com/questions/38972736/… Commented Jul 11, 2018 at 8:28
  • 1
    Do you care for comments and blank lines in the code? If not, you could simply do this, for each function: type func_name | sed 1d. Use compgen -A function to get the list of functions after sourcing your script. Commented Jul 22, 2018 at 6:32
  • @codeforester 's comment should be the correct answer Commented Nov 4, 2020 at 7:35

1 Answer 1

1

With a slight variation and using n and d you can accomplish the task, e.g.

sed -n '/efg/,/[}]/{/efg/{n};/[}]/{d};p}'

Example Use/Output

$ sed -n '/efg/,/[}]/{/efg/{n};/[}]/{d};p}'
 # code of efg function

(note: for multi-line functions only, and you can escape if you prefer, e.g. \} instead of using a character-class [}])

Short Synopsis

  • -n suppress printing of pattern space
  • /efg/,/[}]/ for everything between efg and }
  • {/efg/{n}; if matches efg then next line
  • /[}]/{d}; if matches } delete
  • p otherwise print-it
Sign up to request clarification or add additional context in comments.

1 Comment

macos: sed: 1: "/efg/,/[}]/{/efg/{n};/[ ...": extra characters at the end of n command

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.