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

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

我有如下文件内容:

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也尝试过使用,但结果相同。获取准确输出的命令是什么?

答案1

我会用 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

答案2

您正在尝试获取以下形式的结构数据:

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+

我猜想可以使用 或者awk以更易读的方式完成。perlpython

相关内容