How to Use Sed to Find Strings Between Two Patterns – Text Processing with Sed

sedtext processing

I have file content like this:

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+

The output should be like this:

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

I have tried following sed command:

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

But it's not produce what I want.

What would be the solution? I have tried using awk also but same result is coming. What would be the command to get the exact output?

Best Answer

I'd use awk for this:

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

Passing the pattern, use awk's -v option, and then the pattern match operator ~:

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