removing lines between two patterns (not inclusive) with sed

后端 未结 6 484
遇见更好的自我
遇见更好的自我 2020-12-09 20:08

Ok

I know that this is trivial question but: How can i remove lines from files that are between two known patterns/words:

pattern1
garba

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 20:44

    sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*\n//}; p' inputfile
    

    Explanation:

    /pattern1/{         # if pattern1 is found
        p               # print it
        :a              # loop
            N           # and accumulate lines
        /pattern2/!ba   # until pattern2 is found
        s/.*\n//        # delete the part before pattern2
    }
    p                   # print the line (it's either pattern2 or it's outside the block)
    

    Edit:

    Some versions of sed have to be spoon-fed:

    sed -n -e '/pattern1/{' -e 'p' -e ':a' -e 'N' -e '/pattern2/!ba' -e 's/.*\n//' -e '}' -e 'p' inputfile
    

提交回复
热议问题