使用 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/