样本数据:
$ cat -n strings.dat
1 a
2 b
3 s
4 start
5 text
6 more text
7 end of more text
8 end
9 even more text
10 end
一个awk 解决方案使用一个范围(类似于 RavinderSingh13 的帖子),在末尾打印出 OP 的文本消息:
startstring="start" # define start of search block
awk -v ss="${startstring}" ' # pass start of search block in as awk variable "ss"
# search for a range of lines between "ss" and "end":
$0==ss,/^end$/ { if ($0==ss && x==0 ) x=FNR # if this is the first line of the range make note of the line number
print # print the current line of the range
if ($0=="end") # if this is the last line of the range then print our textual message re: start/finish line numbers
printf "\nThe content is between lines %d and %d.\n",x,FNR
}
' strings.dat
注意:$0==ss 和 /^end$/ 测试假定数据文件中没有前导/尾随空格,否则这些测试将失败并且没有范围匹配。
使用startstring="start" 会生成:
start
text
more text
end of more text
end
The content is between lines 4 and 8.
使用startstring="more text" 会生成:
more text
end of more text
end
The content is between lines 6 and 8.
使用startstring="even more text" 会生成:
even more text
end
The content is between lines 9 and 10.
使用startstring="water" 会生成:
--no output--
注意:如果 OP 使用startstring="end",结果与预期不符;虽然可以添加更多代码来解决这种情况,但我将暂时跳过这种情况。