如何使用sed查找2种模式之间的字符串?

我有这样的文件内容:

aaa accounting exec ... aaa accounting exec ... aaa accounting commands .. aaa accounting commands .. aaa accounting commands .. aaa accounting commands .. aaa accounting commands .. aaa accounting commands .. aaa accounting network .. aaa accounting connection .. aaa accounting system .. ! aaa accounting exec default action-type start-only group tacacs+ ! aaa accounting exec default stop-only group tacacs+ 

输出应该是这样的:

 aaa accounting exec default .. aaa accounting exec default action-type start-only group tacacs+ ! aaa accounting exec default .. 

我试过跟随sed命令:

 sed -n '/aaa accounting exec default/,/!/p' AboveFileContent.txt 

但它并不能产生我想要的东西。

什么是解决方案? 我也试过使用awk但结果相同。 获得确切输出的命令是什么?

我使用awk:

 awk ' /aaa accounting exec default/ {print; exec=1; next} exec { if (/^ /) {print; next} else if (/^!/) {print} exec=0 } ' filename 

传递模式,使用awk的-v选项,然后使用模式匹配运算符~

 awk -v patt='aaa accounting exec default' ' $0 ~ patt {print; exec=1; next} exec { if (/^ /) {print; next} else if (/^!/) {print} exec=0 } ' filename 

您正试图以以下forms获取数据结构:

 aaa ... ... ... ! 

您需要让sed意识到缩进块很重要。 粗略的方法可能是在sed编写一个循环:

 sed -n ' # Create a label named 'start' :start # If the line matches the beginning of a block, # jump (branch) to the label named section /aaa accounting exec default/ b section # If we didn't branch, get the next line n # Jump back to the start label b start # The label named section :section # print the line p n # Keep looping to section for the lines we need /^ /,/!/ b section # If we don't have any more lines to loop on, # jump back to the beginning b start ' 

在一行中:

 $ sed -n ':start; /aaa accounting exec default/ b section; n; b start; :section; p; n; /^ /, /!/ b section; b start' test.txt aaa accounting exec default start-stop group tacacs+ aaa accounting exec default action-type start-only group tacacs+ ! aaa accounting exec default stop-only group tacacs+ 

我猜,它可以使用awkperlpython以更易读的方式完成。