[Cialug] Grep Block of Text

Todd Walton tdwalton at gmail.com
Thu Nov 14 13:19:25 UTC 2019


More often than I'd expect, I find myself wanting to grep for a certain
pattern in a certain file, and have it return the entire block of text that
the pattern was in. I wish I had a single command that took three inputs, a
pattern defining the start of the block, a pattern to find, and a pattern
defining the end of the block of text. For example,

[todd ~]$ cat example.conf
class users::people {
    @username { 'chris':
        comment     => 'Chris Manz',
        home        => '/home/chris',
        uid         => '1010',
        pgroup      => '400',
        groups      => ['it','admins'],
        password    => '$1$3PbnUhBE6hPVP4E10',
        shell       => '/bin/bash',
        ensure      => 'absent',
        expiry      => '2019-01-01'
    }
    @username { 'kellid':
        comment     => 'Kelli Deacon',
        home        => '/home/kellid',
        uid         => '1051',
        pgroup      => '400',
        groups      => ['it','admins'],
        password    => '$6$KBpSaACi14vny/xeE1',
        shell       => '/bin/bash',
        ensure      => 'absent',
        expiry      => '2019-01-01'
    }
    @username { 'dalef':
        comment     => 'Dale Fitzgerald',
        home        => '/home/dalef',
        uid         => '1023',
        pgroup      => '400',
        groups      => ['it','admins'],
        password    => '$1$jfFSl.A15w.0m1gb/1',
        shell       => '/bin/bash',
        ensure      => 'absent',
        expiry      => '2016-09-07'
    }

[todd ~]$ grep-block --pcre --begin '^\s+ at username' --pattern
'^.*home.*dalef..$' --end '^\s+\}' example.conf
    @username { 'dalef':
        comment     => 'Dale Fitzgerald',
        home        => '/home/dalef',
        uid         => '1023',
        pgroup      => '400',
        groups      => ['it','admins'],
        password    => '$1$jfFSl.A15w.0m1gb/1',
        shell       => '/bin/bash',
        ensure      => 'absent',
        expiry      => '2016-09-07'
    }

[todd ~]$ apropos suggestions?
suggestions?: nothing appropriate.

Though the awk answer doesn't seem to work, here's one StackOverflow
question:
https://stackoverflow.com/questions/19926634

Here's some good suggestions for a slightly different scenario (matching on
the delimiters, not on the innards):
https://unix.stackexchange.com/questions/122313/how-to-grep-blocks-or-i-should-use-awk-ack

And also, gee golly, it sure would be nice to use Perl-compatible regular
expressions instead of POSIX. I know I can use awk with RS set to something
other than newline, but I want a more general solution, and... PCREs.

--
Todd


More information about the Cialug mailing list