How to grep on gdb print How to grep on gdb print unix unix

How to grep on gdb print


(gdb) print *this | grep

The "standard" way to achieve this is to use Meta-X gdb in emacs.

An alternative:

(gdb) set logging on(gdb) print *this(gdb) set logging off(gdb) shell grep attribute gdb.txt

The patch mentioned by cnicutar sure looks attractive compared to the above. I am guessing the reason it (or its equivalent) was never submitted is that most GDB maintainers use emacs, and so don't have this problem in the first place.


You can use pipe command

>>> pipe maintenance info sections | grep .text [15]     0x5555555551c0->0x5555555554d5 at 0x000011c0: .text ...>>> pipe maintenance info sections | grep .text | wc       1      10     100


The simplest way is to exploit gdb python. One-liner:

gdb λ py ["attribute" in line and print(line) for line in gdb.execute("p *this", to_string=True).splitlines()]

Assuming you have enabled history of commands, you can type this just once, and later then press Ctrl+R b.exec to pull it out of history. Next simply change attribute and *this per your requirements.


You can also make this as simple as this:

gdb λ grep_cmd "p *this" attribute

For that just add the following to your .gdbinit file:

pyclass GrepCmd (gdb.Command):    """Execute command, but only show lines matching the pattern    Usage: grep_cmd <cmd> <pattern> """    def __init__ (_):        super ().__init__ ("grep_cmd", gdb.COMMAND_STATUS)    def invoke (_, args_raw, __):        args = gdb.string_to_argv(args_raw)        if len(args) != 2:            print("Wrong parameters number. Usage: grep_cmd <cmd> <pattern>")        else:            for line in gdb.execute(args[0], to_string=True).splitlines():                if args[1] in line:                    print(line)GrepCmd() # required to get it registeredend