Shell Tricks: Extract text between two regexes

To extract text between two regular expressions, use sed -n '/first_regex/second_regex/p'.

For instance, to ad-hoc extract the function definition of the test tsync_override_log_subdomains_off, use:

sed -n '/TEST_F(audit, tsync_override_log_subdomains_off)/,/^}/p' \
    tools/testing/selftests/landlock/audit_test.c

This assumes that the function ends with a single } on an individual line. But that tends to be a given.

awk offers similar features. This invocation finds the definitions of static functions with report_fixup in their names, and prefixes these findings with the filenames:

awk '/^static.*report_fixup/,/^}/ { print FILENAME, $0; }' *.c

But well, awk is awkward.

Comments