shell - 如何在两个相同的标记模式之间获取特定数据

标签 shell awk sed grep sh

使用 awk 或 sed ,我如何选择出现在两个相同标记模式之间的线?可能有多个部分标有这些模式。

例如:假设文件包含:

$$$
lines between dollar and AT
@@@
lines between first and second AT
@@@
lines between second and third AT
@@@
lines between third and fourth AT
@@@

使用

cat 2.txt | sed -n '/$$$/,/@@@/p'

我得到 $$$ 和第一次出现的 @@@ 之间的内容。

我的疑问是,如何在说第一次和第三次出现@@@之间获取内容

预期输出是:

lines between first and second AT
@@@
lines between second and third AT

最佳答案

awk 似乎是这项工作的更明智的工具,主要是因为它允许您比 sed(也就是说,根本)更容易地在命令行上指定参数,并且因为它可以理智地处理数字。

我会用

awk -v pattern='^@@@$' -v first=1 -v last=3 '$0 ~ pattern { ++count; if(count == first) next } count == last { exit } count >= first' 2.txt

工作原理如下:

$0 ~ pattern {              # When the delimiter pattern is found:
  ++count                   # increase counter.
  if(count == first) {      # If we found the starting pattern
    next                    # skip to next line. This handles the fencepost.
  }
}
count == last {             # If we found the end pattern, stop processing.
  exit
}
count >= first              # Otherwise, if the line comes after the starting
                            # pattern, print the line.

关于shell - 如何在两个相同的标记模式之间获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35194641/

相关文章:

Linux 剪切、粘贴

linux - 为不同的变量重复 awk 文件的任务

bash - 打印同一行两个字符串之间的文本

bash - 有没有办法捕获管道命令中的失败?

regex - 在 Mac 终端中一起使用 lsof 和 awk 的奇怪行为?

shell - 一行中的多个字符串的 grep

linux - 如何在文本/模式的前两个实例之间获取单词?

awk - 用于字符串到 shell 中 csv 列的整数转换的 Sed/awk

linux - 如何使用grep捕获转义序列,例如终端颜色

Android:使用 ADB shell 读取 APN