SED: Matching on 2 patterns on the same line

前端 未结 3 483
长发绾君心
长发绾君心 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 10:46

    this strips out multiline comments as well

    eg

    # cat file
    blah blah /* comment */
    words1
    words2
    /* multiline
       comments
    /*
    end
    
    $ awk -vRS='*/'  '{ gsub(/\/\*.*/,""); }1' file
    blah blah
    
    words1
    words2
    

    you can add another filter to sed 's|\/\/.*||' to filter out // comments as well

    0 讨论(0)
  • 2021-01-21 10:51

    Try

    sed '/^\/\*.*\*\/$/ d' filename

    The key here is that you can sorta combine two regex patterns into one, simply by connecting them with .*, which matches "any number of any character". Of course, this enforces an ordering between the two. The first pattern ^\/\* must occur before the second one \*\/$ for this particular pattern to match.

    Also, since * has special meaning in regex, be sure to escape your astrices, just as you have to escape your slashes.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题