3 ms·
Ok; my favorite awk one-liner I found somewhere and learnt by heart is for extracting "blocks of text between some starting pattern/line and some ending pattern
by akavel 8y ago
Ok; my favorite awk one-liner I found somewhere and learnt by heart is for extracting "blocks of text between some starting pattern/line and some ending pattern/line"; most often, that would be "functions with particular name, with their whole body". Brace yourselves:
awk '/^func Test/{p=1}; p; /^}/{p=0}'
EXPLANATION
First of all, this is 3 separate "commands", separated by ';'. In order:
/^func Test/ {p=1}
— if line matches regexp '^func Test' (i.e., starts with "func Test"), then set variable p to 1 (a.k.a. "True").
p
— equivalent to any of:
p { print }
p { print $0 }
{ if (p) { print $0 } }
meaning: if variable p is true-ish (in case of this script, if p==1), then print current line (if action is not specified after a condition, then it's by default {print}).
/^}/ {p=0}
— you may have guessed already now: stop printing after encountering end of function (line starting with '}').
- dbolgheroni 8y agoYou can get the same behaviour with sed without "programmability": $ sed -n '/^func Test/,/^}/p' file Which means: match 'func Test' at the beginning of a line and print (p command at the end) until you find a line beginnning with '}'. This is because the print command (p) accepts 2 addresses to delimit a range. I used regexes as addresses but, for instance, can use line numbers also: $ sed -n '10,20p' file This prints file's line from 10 to 20. By default, sed prints the pattern space (modifications to each line) at the end of the script. The -n I used is to avoid that.
- akavel 8y agoHah, lol, thanks, Today I Learnt ;) Will try using this next time, probably. That said, there's one extra advantage with the awk script, that by rearranging the expressions appropriately, I can choose whether to include or exclude the the first and last line in the output (i.e. 'FIRST; p; LAST' vs. 'FIRST; LAST; p' or 'p; FIRST; LAST', etc.) Is this also possible with sed? :)