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

Varun Chandak
  • 943
  • 1
  • 8
  • 25

1 Answers1

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
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • macos: `sed: 1: "/efg/,/[}]/{/efg/{n};/[ ...": extra characters at the end of n command` – JOhn Sep 26 '19 at 23:12