Reputation: 971
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
Upvotes: 1
Views: 917
Reputation: 84551
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 }
deletep
otherwise print-itUpvotes: 1