SED: Matching on 2 patterns on the same line

前端 未结 3 526
长发绾君心
长发绾君心 2021-01-21 10:19

Hi I want to delete a line using sed if it matches 2 regular expressions in the same line. EG the line starts with /* and end with */ (comment). The following script will do m

3条回答
  •  误落风尘
    2021-01-21 11:02

    For your specific problem, you can do something along the lines recommended by @echo. However, if you need a more general solution, for instance, one where the regexp matches aren't anchored at one end of the line or the other, or might be in either order on the line, or might even overlap, you'll something like the following sed script:

    /regexp1/! b notboth
    /regexp2/! b notboth
    :both
    # sed commands if both patterns match
    n
    :notboth
    # sed commands if at least one pattern doesn't match
    n
    

    This uses sed's branching abilities. The b command branches to the named label if the pattern match succeeds, and the trailing ! on the pattern inverts the sense of the match. so, roughly,

    Put this in a file, say foo.sed, and run it as sed -f foo.sed.

提交回复
热议问题