仅打印从开始到结束点的内容

时间:2013-11-25 15:23:26

标签: perl sed awk grep

只想打印从开始到结束点的那些

示例:

Started at Mon Nov 25 14:30:02 ALMT 2013
Load average for db1 is 10 which is less than 100
Load average for db2 is 3 which is less than 100
Load average for db3 is 6 which is less than 100
Load average for db4 is 5 which is less than 100
Load average for db5 is 5 which is less than 100
Mon Nov 25                                                                                 page
some other data
some other data
some other data

预期:

Started at Mon Nov 25 14:30:02 ALMT 2013
Load average for db1 is 10 which is less than 100
Load average for db2 is 3 which is less than 100
Load average for db3 is 6 which is less than 100
Load average for db4 is 5 which is less than 100
Load average for db5 is 5 which is less than 100
Mon Nov 25                                                                                 page

我试着用它:

perl -0777 -lpe 's|Started .*? page||xsg' 1

但是删除了我要打印的整个区域。

4 个答案:

答案 0 :(得分:3)

它可以成功:

$ awk '/^Started/ {p=1} p; /page$/ {p=0}' file
Started at Mon Nov 25 14:30:02 ALMT 2013
Load average for db1 is 10 which is less than 100
Load average for db2 is 3 which is less than 100
Load average for db3 is 6 which is less than 100
Load average for db4 is 5 which is less than 100
Load average for db5 is 5 which is less than 100
Mon Nov 25                                                                                 page
  • /^Started/ {p=1}当找到以“已开始”开头的字符串时,则标记p设置为1.
  • 如果标记p为真,则
  • p打印该行。
  • /page$/ {p=0}当找到以“page”结尾的字符串时,标志p将设置为0.

此外,(thanks 1_CR):

awk '/^Started/,/page$/' file

答案 1 :(得分:2)

。但请注意,如果遇到“开始”标记而不是“结束”,它将打印从开始标记到文件结尾的所有内容

sed -n '/^Started/, /page/p' file

答案 2 :(得分:1)

尝试以下方法:

$ perl -0777 -lpe 's|.*(Started .*? page).*|$1|xsg' 1

答案 3 :(得分:1)

perl -0777 -ne 'print /(Started .*? page)/xsg' 1