linux - 如何在文本中搜索多行模式并获得最后一次出现?

标签 linux command-line awk

我需要在文件中找到 pgp 加密消息。它们以 -----BEGIN PGP MESSAGE----- 开始,以 -----END PGP MESSAGE----- 结束。

到目前为止我有这个:

$ tail -200 somefile | awk '/-----BEGIN PGP MESSAGE-----/,/-----END PGP MESSAGE-----/'

它正在查找所有出现的事件,但我只想要最后一个。

最佳答案

你可以使用 sed:

tail -200 somefile | sed -n '
  # only consider lines between BEGIN and END
  /-----BEGIN PGP MESSAGE-----/,/-----END PGP MESSAGE-----/ {
    # if the beginning line, clear the hold space
    /-----BEGIN PGP MESSAGE-----/{x;d}
    # add the line to the hold space
    H
  };
  # print the hold space at the end
  ${x;p}'

这个sed注释(注释是为了解释,在实际命令中不需要),“BEGIN”和“END”之间的任何行都将添加到保留空间,并在每个“BEGIN”时清除保留空间"然后打印在最后。

编辑:

为了完整起见,这里是没有注释且在一行中的版本(与上面相同)

tail -200 somefile | sed -n '/-----BEGIN PGP MESSAGE-----/,/-----END PGP MESSAGE-----/{/-----BEGIN PGP MESSAGE-----/{x;d};H};${x;p}'

关于linux - 如何在文本中搜索多行模式并获得最后一次出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918642/

相关文章:

google-chrome - 主机规则谷歌浏览器,添加配置

java - 如何从命令行参数设置 java.util.logging.ConsoleHandler.level?

python 执行shell命令并继续而不等待并在执行前检查是否运行

linux - 用于创建新选项卡以运行 bash 命令的 Apple 脚本

linux - Emscripten 和空方 block

linux - 使用 yocto 添加第三方 linux 内核模块

linux - 在 linux 终端中使用 awk 命令忽略重复?

linux - pp (PAR) 在哪里解压添加 (-a) 文件?

bash - 文件列表中带有awk的文件大小总和

bash - 通过awk将文件中的数值更改为字符