如何在 gdb 上进行 grep 打印

问题描述 投票:0回答:4

有没有办法在 gdb 中 grep 打印命令的输出?就我而言,我正在使用 gdb 调试核心转储,并且我正在调试的对象包含大量元素。

我发现很难寻找匹配的属性,即:

(gdb) print *this | grep <attribute>
debugging unix gdb
4个回答
18
投票

您可以使用

pipe
命令

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

>>> pipe maintenance info sections | grep .text | wc 
      1      10     100

10
投票

(gdb)打印*这个| grep

实现此目的的“标准”方法是在

Meta-X gdb
中使用
emacs

替代方案:

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

cnicutar 提到的补丁与上面的相比确实看起来很有吸引力。我猜测它(或其等效项)从未提交的原因是大多数 GDB 维护者使用

emacs
,因此一开始就没有这个问题。


6
投票

最简单的方法是利用 gdb python。单行:

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

假设您已启用命令历史记录,您只需键入一次,然后按 Ctrl+R b.exec 将其从历史记录中提取。接下来只需根据您的要求更改

attribute
*this


您也可以像这样简单地实现:

gdb λ grep_cmd "p *this" attribute

为此,只需将以下内容添加到您的

.gdbinit
文件中:

py
class 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 registered
end

0
投票

我知道这是一篇旧帖子,但因为我发现它想做同样的事情,我想我会在 Hi-Angel 的答案中添加一点,说你可以在 python 输出中以红色突出显示搜索词,方法是替换打印以下行:

print(line.replace(args[1], "\033[91m"+args[1]+"\033[0m"))

这仅使用

ascii escape
命令来设置颜色,因此应该适用于 Linux 和 Windows 终端,并且您可以轻松更改颜色。

抱歉,没有足够的代表将此添加为评论。

© www.soinside.com 2019 - 2024. All rights reserved.