首页 > 解决方案 > 如何使用 sed 删除从 pattern_1 到第二次出现 pattern_2 的行?

问题描述

我需要找到一个命令来使用 sed 删除从 pattern_1 到 pattern_2 的第二次出现(包括 pattern_1 和 pattern_2 的第二次出现)的行。

random_line_1
pattern_1
pattern_2
random_line_3
random_line_4
random_line_5
pattern_2
random_line_6

我需要获得:

random_line_1
random_line_6

我尝试了很多命令,灵感来自我在各处发现的东西,但没有任何效果......

任何想法?

标签: bashsed

解决方案


请您尝试以下方法:

sed -n '
/pattern_1/ {                   ;# if the line matches "pattern_1"
    :l1                         ;# then enter a loop for "pattern_2"
    n
    /pattern_2/ {               ;# if the line matches the 1st "pattern_2"
        :l2                     ;# then enter an inner loop for next "pattern_2"
        n
        /pattern_2/ {           ;# if the line matches the 2nd "pattern_2"
            b                   ;# then exit the loop
        }
        b l2                    ;# else jump to "l2"
    }
    b l1
}
p                               ;# print the pattern space
' file

推荐阅读