如何在两个相同的标记模式之间获取特定数据
How to get particular data between two same marker patterns
使用 awk 或 sed ,我如何 select 出现在两个相同标记模式之间的行?可能有多个部分标有这些模式。
例如:假设文件包含:
$$$
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 '[=10=] ~ pattern { ++count; if(count == first) next } count == last { exit } count >= first' 2.txt
其工作原理如下:
[=11=] ~ 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.
使用 awk 或 sed ,我如何 select 出现在两个相同标记模式之间的行?可能有多个部分标有这些模式。
例如:假设文件包含:
$$$
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 '[=10=] ~ pattern { ++count; if(count == first) next } count == last { exit } count >= first' 2.txt
其工作原理如下:
[=11=] ~ 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.